O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

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

Chapter    9

Optionals

In situations where you can’t be sure a variable has a value present, you can use optionals. An optional is a variable that can have either an assigned value or no value at all. Using optionals is an alternative to setting objects to nil. Optionals can be used with any type in Swift including numbers, strings, and objects.

You declare optionals like variables or constants, but you must include a ? after the type declaration (see Listing 9-1). Like variables and constants, the data type of an optional may be inferred.

Listing 9-1. String Optional Declaration

var s:String?

The variable s in Listing 9-1 is declared as an optional, and the starting value is nil.

Forced Unwrapping

If you are sure that an optional has a value, ...

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