O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Optional variables

All the variables we have looked at so far are considered to be non-optional variables. This means that the variables are required to have a non-nil value; however, there are times when we may want or need our variables to contain no or nil values.

In Swift, an optional variable is a variable that we can assign nil (no value) to. Optional variables and constants are defined using the ? (question mark).

The following Playground will show us how to define an optional type and what happens if we assign a nil value to a non-optional variable:

Notice the error we receive when we try to assign a nil value to the non-optional variable. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required