Search code examples
iosswiftoption-typeunwrap

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.

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? I've even tried "if action != nil", but it still somehow slips through and causes a SIGABRT.


Solution

  • NSNull is a special value typically resulting from JSON processing. It is very different from a nil value. 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
    }