The error happens because the variable contains no value when you try to unwrap it.
if let unwrappedAuthorName: String = authorName {
print("Author is (unwrappedAuthorName)")
} else {
print("No author.")
}
This special syntax rids the type of the optional. If the optional contains a value,then the code executes theside of thestatement,within which you automatically unwrap thevariable because you know it's safe to do so. If the optional doesn't contain a value,then the code executes theside of thestatement. In that case,thevariable doesn't even exist.
You can see howbinding is much safer than force unwrapping,andyou should opt for it whenever possible.
You can even unwrap multiple values at the same time,like so:
let authorName: String? = "Matt Galloway"
let authorAge: Int? = 30
if let name: String = authorName,age: Int = authorAge {
print("The author is (name) who is (age) years old.")
} else {
print("No author or no age.")
}
This code unwraps two values. It will only execute thepart of the statement when both optionals contain a value.
There's one final and rather handy way to unwrap an optional. You use it when you want to get a value out of the optional no matter what-and in the case of,you'll use a default value. This is callednil coalescing. Here is how it works:
var optionalInt: Int? = 10
var result: Int = optionalInt ?? 0
The
coalescing happens on the second line,with the double question mark (??). This line means
will equal either the value inside
contains
.