Optional binding

Swift includes a feature known as optional binding, which lets you safely access the value inside an optional. You use it like so:

if let unwrappedAuthorName = authorName { print("Author is (unwrappedAuthorName)")

} else {

print("No author.")

}

You’ll immediately notice that there are no exclamation marks here. This optional binding gets rid of the optional type. If the optional contains a value, this value is unwrapped and stored in, or bound to, the constant unwrappedAuthorName. The if statement then executes the first block of code, within which you can safely use unwrappedAuthorName, as it’s a regular non-optional String.

If the optional doesn’t contain a value, then the if statement executes the else

block. In that case, the unwrappedAuthorName variable doesn’t even exist.

You can see how optional binding is much safer than force unwrapping, and you should use it whenever an optional might be nil. Force unwrapping is only appropriate when an optional is guaranteed contain a value.

Because naming things is so hard, it’s common practice to give the unwrapped constant the same name as the optional (thereby shadowing that optional):

if let authorName = authorName { print("Author is (authorName)")

} else {

print("No author.")

}

You can even unwrap multiple values at the same time, like so:

if let authorName = authorName, let authorAge = authorAge {

print("The author is (authorName) who is (authorAge) years old.")

} else {

print("No author or no age.")

}

This code unwraps two values. It will only execute the if part of the statement when both optionals contain a value.

You can combine unwrapping multiple optionals with additional boolean checks. For example:

if let authorName = authorName, let authorAge = authorAge, authorAge >= 40 {

print("The author is (authorName) who is (authorAge) years old.")

} else {

print("No author or no age or age less than 40.")

}

Here, you unwrap name and age, and check that age is greater than or equal to 40. The expression in the if statement will only be true if name is non-nil, and age is non-nil, and age is greater than or equal to 40.

Now you know how to safely look inside an optional and extract its value, if one exists.

results matching ""

    No results matching ""