Checking for nil Value in Swift Dictionary Extension

Viewed 3433

I have the following code in a playground file:

extension Dictionary {

    func test()  {

        for key in self.keys {
            self[key]
        }
    }
}

var dict: [String: AnyObject?] = [
    "test": nil
]

dict.test()

I will henceforth refer to the line within the for-each loop as the output since it is what's relevant. In this particular instance the output is nil.

When I change the for-each loop to look like this:

for key in self.keys {
    print(self[key])
}

The output is "Optional(nil)\n".

What I really want to do is check the value for nil, but the code:

for key in self.keys {
    self[key] == nil
}

outputs false.

One other thing I tried was the following:

for key in self.keys {
    self[key] as! AnyObject? == nil
}

which produces the error:

Could not cast value of type 'Swift.Optional<Swift.AnyObject>' to 'Swift.AnyObject'

Any help with this is much appreciated!

2 Answers
Related