swift - Switft Dictionary 问题 'String?' is not convertible to 'String' ;您的意思是使用 'as!' 强制向下转换吗?

标签 swift dictionary

我是 Swift 和 ObjC 的新手,无法让这段简单的代码发挥作用。我收到错误“字符串?”不可转换为“字符串”;你是不是想用 'as!'强制垂头丧气?

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

    var str : String

    str = data["Score"] as String //<<<I get the error here

当我把它改成as!我知道收到此警告:Forced cast from 'String?' to 'String' 只解包选项;您是要使用“!”吗?

有什么想法可以从字典中提取字符串以便我可以使用它吗?

最佳答案

您的字典中可能没有设置键“Score”,可能会返回 nil。使用此代码解包可选:

if let score = data["Score"] {
    str = score
}

因为你已经打开了 contextDictionary<String, String> , Swift 会自动推断出 score 的类型作为字符串。

关于swift - Switft Dictionary 问题 'String?' is not convertible to 'String' ;您的意思是使用 'as!' 强制向下转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628285/

相关文章:

arrays - 错误 438 对象不支持此属性或方法 - 带字典的类对象

ios - 在自己的应用程序中打开来自其他应用程序的文件

php - iOS - Swift 中的密码加密

python - 将数据框转换为具有多个值的字典

swift - 如何从 Swift 字典中打印一些键

ios - 在 Swift 中将任何字典数组转换为字符串

c# - 字符串编码错误(Windows 10 + Visual Studio 2015 + Net 4.6)

ios - 将服务器响应加载到 UICollectionView

swift - 如何根据 if 语句在 swift 中的结果创建不同类型的变量?

ios - Swift 2.2 AVPlayer 错误处理