Book Image

Learning Swift

By : Andrew J Wagner
Book Image

Learning Swift

By: Andrew J Wagner

Overview of this book

Table of Contents (18 chapters)
Learning Swift
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Implicitly unwrapped optionals


There is a second type of optional called an implicitly unwrapped optional. There are two ways to look at what an implicitly unwrapped optional is. One way is to say that it is a normal variable that can also be nil. The other way is to say that it is an optional that you don't have to unwrap to use. The important thing to understand about them is that like optionals, they can be nil, but like a normal variable, you do not have to unwrap them.

You can define an implicitly unwrapped optional with an exclamation mark (!) instead of a question mark (?) after the type name:

var name: String!

Just like with regular optionals, implicitly unwrapped optionals do not need to be given an initial value because they are nil by default.

At first, this may sound like it is the best of both worlds, but in reality, it is more like the worst of both worlds. Even though an implicitly unwrapped optional does not have to be unwrapped, it will crash your entire program if it is nil...