【问题标题】:Swift: Unwrapping Optionals and NSNullSwift:解包 Optionals 和 NSNull
【发布时间】:2017-06-28 15:48:40
【问题描述】:
if let action = self.info?["action"] {
    switch action as! String {
        ....
    }
} else {...}

在此示例中,“action”始终作为 key 在 self.info 中存在。

一旦第二行执行,我得到:

Could not cast value of type 'NSNull' (0x1b7f59128) to 'NSString' (0x1b7f8ae8).

知道即使我打开了 action 怎么可能是 NSNull 吗?我什至尝试过“if action != nil”,但它仍然以某种方式溜过并导致 SIGABRT。

【问题讨论】:

  • 您尝试解包的可能不是字符串
  • self.info 是 [String : AnyObject] 类型的字典,但值始终是字符串。无论如何都不应该强迫沮丧的工作?
  • 为什么在声明字符串时不将操作有条件地强制转换为字符串?像这样:if let action = self.info?["action"] as? String {...
  • 不确定您使用的是哪个版本的 Swift,但从 Swift 3 开始,String 不符合 AnyObject。请改用[String:Any]
  • 另外从错误消息中你可以看到你得到的是NSNull而不是一个字符串,并且检查nil不会有帮助,因为NSNull是一个实际的对象。

标签: ios swift optional unwrap


【解决方案1】:

NSNull 是一个特殊值,通常由 JSON 处理产生。它与nil 值非常不同。而且您不能将对象从一种类型强制转换为另一种类型,这就是您的代码失败的原因。

您有几个选择。这是一个:

let action = self.info?["action"] // An optional
if let action = action as? String {
    // You have your String, process as needed
} else if let action = action as? NSNull {
    // It was "null", process as needed
} else {
    // It is something else, possible nil, process as needed
}

【讨论】:

    【解决方案2】:

    试试这个。因此在第一行中,首先检查“action”是否存在有效值,然后检查该值是否为 String 类型

    if let action = self.info?["action"] as? String {
        switch action{
            ....
        }
    } else {...}
    

    【讨论】:

      【解决方案3】:
      if let action = self.info?["action"] { // Unwrap optional
      
         if action is String {  //Check String
      
            switch action {
              ....
            }
      
        } else if action is NSNull { // Check Null
      
          print("action is NSNull")
      
        } else {
      
          print("Action is neither a string nor NSNUll")
      
        }
      
      } else {
      
          print("Action is nil")
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        • 2019-06-15
        • 1970-01-01
        相关资源
        最近更新 更多