Swift: 解包选项和 NSNull

Swift: Unwrapping Optionals and NSNull

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

在此示例中,"action" 始终作为 self.info 中的键存在。

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

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

知道即使我打开了 action 也可以是 NSNull 吗?我什至尝试过 "if action != nil",但它仍然以某种方式漏掉并导致 SIGABRT。

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
}

试试这个。所以在第一行中,首先检查 "action" 是否存在有效值,然后检查该值是否属于 String

类型
if let action = self.info?["action"] as? String {
    switch action{
        ....
    }
} else {...}
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")

}