Optionals

Swift types can be optional, which is indicated by appending ? to a type name.

var anOptionalFloat: Float?
var anOptionalArrayOfStrings: [String]?
var anOptionalArrayOfOptionalStrings: [String?]?

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 this 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 of instrument readings:

var reading1: Float
var reading2: Float
var reading3: Float

Sometimes, an instrument might malfunction and not report a reading. ...

Get iOS Programming: The Big Nerd Ranch Guide 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.