O'Reilly logo

Cocoa Programming for OS X: The Big Nerd Ranch Guide by Aaron Hillegass, Adam Preble, Nate Chandler

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

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

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