nuvaryan
nuvaryan

Reputation: 237

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.

Upvotes: 0

Views: 1578

Answers (3)

Krunal
Krunal

Reputation: 79776

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")

}

Upvotes: 0

Fangming
Fangming

Reputation: 25260

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

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

Upvotes: 0

rmaddy
rmaddy

Reputation: 318934

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
}

Upvotes: 1

Related Questions