Testing Dictionaries for the Presence of Values

Dictionaries return optionals when you try to access items. Therefore, you might want to place them into value bindings. If you don’t need the value of the key you are testing, you can instead use a regular if statement, like this:

if people[198364775] {    println("Got him")} else {    println("No one with that Social Security number")}

If you do in fact want the unwrapped value from the optional (if it does succeed), you can use full value binding, like this:

if let person = people[198364775] {    println("Got \(person)")} else {    println("No one with that social security number")}

Now you will have the unwrapped value of the optional ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.