Switft Dictionary问题'String?' 不能转换为'String'; 你的意思是用'as!' 迫使低垂?

Ark*_*on3 0 dictionary swift

我是Swift和ObjC的新手,无法使用这么简单的代码.我收到错误'String?' 不能转换为'String'; 你的意思是用'as!' 迫使低垂?

    guard let data = context as? Dictionary<String,String> else {return}

    var str : String

    str = data["Score"] as String //<<<I get the error here
Run Code Online (Sandbox Code Playgroud)

当我把它改为!我知道得到这个警告:来自'String?'的强迫演员 'String'只展开选项; 你的意思是用'!'?

任何想法如何从字典中提取字符串,以便我可以使用它?

Rai*_*arz 5

有可能,您的词典中没有设置关键"得分",并且可能返回零.使用此代码解包可选:

if let score = data["Score"] {
    str = score
}
Run Code Online (Sandbox Code Playgroud)

既然你已经解开contextDictionary<String, String>,SWIFT将自动推断的类型score为String.