read

We all assume an if-let way of unwrapping optional works as it is.

Example:

let json: AnyObject = ["x": "y"]
if let foo = json["foo"] {
    print("Should not see this since json[\"foo\"] is nil!")
}

In the above, we should not see the print statement since json["foo"] is nil.

Yet, we will see the print!

This is because AnyObject is evil. It will ruin things, run wild, and unpredictable.

To fix, you need to cast to the type that you know the unwrapped optional will be eg. String:

let json: AnyObject = ["x": "y"]
if let foo = json["foo"] as? String {
    print("Should not see this since json[\"foo\"] is nil!")
}

Now, you don’t see the print!

UPDATE: An easier way is

if let foo = json["foo"] ?? {

Image

@samwize

¯\_(ツ)_/¯

Back to Home