Optionals

Swift has a generic optional type, Optional<T>. In practice, an optional is indicated by appending ? to a type name:

v​a​r​ ​a​n​O​p​t​i​o​n​a​l​F​l​o​a​t​:​ ​F​l​o​a​t​?​
v​a​r​ ​a​n​O​p​t​i​o​n​a​l​A​r​r​a​y​O​f​S​t​r​i​n​g​s​:​ ​[​S​t​r​i​n​g​]​?​
v​a​r​ ​a​n​O​p​t​i​o​n​a​l​A​r​r​a​y​O​f​O​p​t​i​o​n​a​l​S​t​r​i​n​g​s​:​ ​[​S​t​r​i​n​g​?​]​?​

An optional lets you express the possibility that a variable may not store a value at all. The value of an optional will either be an instance of the specified type or nil.

Throughout the book, you will have many chances to use optionals. What follows is an example to get you familiar with the syntax so that you can focus on the use of the optionals later.

Imagine a group ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.