简体   繁体   English

Swift:展开Optionals和NSNull

[英]Swift: Unwrapping Optionals and NSNull

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

In this example, "action" always exists as a key in self.info. 在此示例中,“ action”始终作为self.info中的键存在。

Once the second line executes, I get: 一旦第二行执行,我得到:

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

Any idea how action can be NSNull even though I unwrapped it? 知道即使我展开了动作,NSNull怎么能动作呢? I've even tried "if action != nil", but it still somehow slips through and causes a SIGABRT. 我什至尝试了“ if action!= nil”,但它仍然以某种方式滑倒并导致SIGABRT。

NSNull is a special value typically resulting from JSON processing. NSNull是一个特殊值,通常由JSON处理产生。 It is very different from a nil value. 它与nil值有很大不同。 And you can't force-cast an object from one type to another which is why your code fails. 而且您不能将对象从一种类型强制转换为另一种类型,这就是代码失败的原因。

You have a few options. 您有几种选择。 Here's one: 这是一个:

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
}

Try this out. 试试看 So in the first line, check first if there is a valid value for "action", then if that value is in type String 因此,在第一行中,首先检查“ 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")

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM