Force unwrapping
The error message gives an indication of the solution: It tells you that the optional is not unwrapped. You need to unwrap the value from its box. It’s like Christmas!
Let’s see how that works. Consider the following declarations:
var authorName: String? = "Matt Galloway"
var authorAge: Int? = 30
There are two different methods you can use to unwrap these optionals. The first is known as force unwrapping, and you perform it like so:
var unwrappedAuthorName = authorName! print("Author is (unwrappedAuthorName)")
This code prints:
Author is Matt Galloway
Great! That’s what you’d expect.
The exclamation mark after the variable name tells the compiler that you want to look inside the box and take out the value. The result is a value of the wrapped type. This means unwrappedAuthorName is of type String, not String?.
The use of the word “force” and the exclamation mark ! probably conveys a sense of danger to you, and it should. You should use force unwrapping sparingly. To see why, consider what happens when the optional doesn’t contain a value:
authorName = nil
print("Author is (authorName!)")
This code produces the following runtime error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The error occurs because the variable contains no value when you try to unwrap it. What’s worse is that you get this error at runtime rather than compile time – which means you’d only notice the error if you happened to execute this code with some invalid input. Worse yet, if this code were inside an app, the runtime error would cause the app to crash!
How can you play it safe?
To stop the runtime error here, you could wrap the code that unwraps the optional in a check, like so:
if authorName != nil { print("Author is (authorName!)")
} else {
print("No author.")
}
The if statement checks if the optional contains nil. If it doesn’t, that means it contains a value you can unwrap.
The code is now safe, but it’s still not perfect. If you rely on this technique, you’ll have to remember to check for nil every time you want to unwrap an optional. That will start to become tedious, and one day you’ll forget and once again end up with the possibility of a runtime error.
Back to the drawing board, then!