Optionals

Optionals are values which can represent the absence of a value. Optionals have two cases: either there is a value, or there is nothing.

An optional type is declared using the ? suffix for another type. For example, Int is a non-optional integer, and Int? is an optional integer, i.e. either nothing, or an integer.

The value representing nothing is nil.

// Declare a constant which has an optional integer type,
// with nil as its initial value.
//
let a: Int? = nil

// Declare a constant which has an optional integer type,
// with 42 as its initial value.
//
let b: Int? = 42

// Invalid: `b` has type `Int?`, which does not support arithmetic.
b + 23

// Invalid: Declare a constant with a non-optional integer type `Int`,
// but the initial value is `nil`, which in this context has type `Int?`.
//
let x: Int = nil

Optionals can be created for any value, not just for literals.

A non-optional type is a subtype of its optional type.

Optional types may be contained in other types, for example arrays or even optionals.

Last updated

Was this helpful?