【问题标题】:Switft Dictionary problem 'String?' is not convertible to 'String'; did you mean to use 'as!' to force downcast?Swift 字典问题“字符串?”不能转换为“字符串”;你的意思是用'as!'强迫沮丧?
【发布时间】:2018-12-05 08:45:53
【问题描述】:

我是 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!我知道收到此警告:从“字符串”强制转换? to 'String' 只解开选项;您的意思是使用“!”吗?

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

【问题讨论】:

  • 您不需要强制转换,但执行data["Score"] 的结果可能为空
  • 您应该了解以下内容。每次你在 Objective-C 中得到NSString - 它可能是零。在 Swift 中,它取决于上下文。对于Dictionary,它将是String?。这意味着字符串可以为零。你读过苹果关于 Swift 的书吗? :)

标签: swift dictionary


【解决方案1】:

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

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

由于您已经将context 解包为Dictionary&lt;String, String&gt;,Swift 会自动将score 的类型推断为字符串。

【讨论】:

    【解决方案2】:

    您不需要强制转换,因为data 字典将始终返回可选的String 类型,您可以使用guard 语句

    guard let str = data[Score] else { return }
    // Your code here
    

    【讨论】:

      【解决方案3】:

      下标Dictionary 返回的类型是可选的,因为使用不存在的键对其下标是有效的。因此,根据错误消息,在具有String 值的字典中,返回类型为String?

      如果您确定该键始终存在于字典中,则可以将其强制解包为 data["Score"]! 以创建类型 String(不进行强制转换,但如果不存在则崩溃)。否则以某种方式处理nil,例如if let str = data["Score"]str = data["Score"] ?? "0"

      【讨论】:

        【解决方案4】:

        这样使用:

        if let dataDictionary = context as? [String: Any] {
                if let someString = dataDictionary["score"] as? String {
                    print(someString)
                }
            }
        

        【讨论】:

          【解决方案5】:

          我们不知道您正在处理什么样的数据,但您可能会得到一个实际上类型为 [String: String] 的字典,在这种情况下,您会:

          func getData(context: [String: String]) {
              guard let str = context["Score"] else {
                  return
              }
              print(str)
          }
          

          ...或者你真的得到了[String: Any] 类型的字典(在数据库字典中更常见),在这种情况下你会:

          func getData(context: [String: Any]) {
              guard let str = context["Score"] as? String else {
                  return
              }
              print(str)
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-09-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-05-26
            • 1970-01-01
            相关资源
            最近更新 更多