Mike Nathas
Mike Nathas

Reputation: 1393

Swift - accessing nil does not crash

I noticed a strange behavior in swift. The following code will print "Not found" as one would expect.

import Cocoa

var array = [["one":"1"]]

for element in array {
    if let check = element["two"] {
        print(check)
    } else {
        print("Not found")
    }
}

Slightly changing the code to

import Cocoa

var array : [AnyObject]?
array = [["one":"1"]]

for element in array! {  
    if let check = element["two"] {
        print(check)
    } else {
        print("Not found")
    } 
}

will print "nil" - that's not what I was expecting as I thought in swift a nil is a "not set" and not a printable object.

Is there something i'm missing? Thanks!

Upvotes: 2

Views: 204

Answers (1)

Charles A.
Charles A.

Reputation: 11123

In the second case, you're actually creating a nested optional, which is generally not a good idea (it only leads to confusion, and I don't know why the compiler allows it frankly). If you put in the line:

let foo = element["two"]

and inspect foo's type, you'll see that it is AnyObject?!. So it's an optional with no value wrapped in an optional. This has the effect of making your if/let statement unwrap the first optional to give you a second optional, which is nil.

Upvotes: 2

Related Questions