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, ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.