【问题标题】:Could not cast value of type 'NSNull' (0x10aa1b600) to 'NSString' (0x10b4dab48)无法将“NSNull”(0x10aa1b600)类型的值转换为“NSString”(0x10b4dab48)
【发布时间】:2016-11-17 00:44:27
【问题描述】:

我的 json 有餐厅的 googleplus 链接,如果餐厅没有任何 googleplus 链接,它会显示 null 但我收到上述错误。

if dict["googlepluslink"] != nil
{
    self.googlepluslink.append((dict["googlepluslink"] as? String)!)
}
else
{
    self.googlepluslink.append(("-" as? String)!)
}

无法将“NSNull”(0x10aa1b600)类型的值转换为“NSString”(0x10b4dab48)

【问题讨论】:

    标签: ios json swift


    【解决方案1】:
        self.googlepluslink.append((dict["googlepluslink"] as? String)!)
    

    这完全是奇怪和自相矛盾的。

    你从字典里取出一些东西。结果是一个可选值,而且它可以是任何类的对象,例如 NSNull。

    然后您使用 as? 将其转换为字符串?这意味着您将获得一个可选字符串,并且如果字典不包含任何内容或无法转换为字符串的内容,则不会崩溃!

    然后你使用 !如果您的可选字符串为 nil,则 崩溃的运算符。这没有任何意义。

    【讨论】:

      【解决方案2】:

      使用if letguard 语句检查dict["googlepluslink"] 是否为字符串,然后根据您可以像下面这样附加数据

      if let link = dict["googlepluslink"] as? String 
      { 
          self.googlepluslink.append(link)
      } 
      else {
          self.googlepluslink.append("-")
      }
      

      【讨论】:

        猜你喜欢
        • 2016-06-06
        • 2017-04-10
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        • 2017-10-30
        • 2018-02-08
        • 2016-07-15
        • 1970-01-01
        相关资源
        最近更新 更多