๐ŸŽ“ A1Learner
๐Ÿ”

Swift Optionals

An optional is a value that either holds a value or holds nothing. The nothing case has its own name, nil.

One optional with a value, one with nil

The first optional holds a string. The second optional holds nil.

var name: String? = "Mia"
var missing: Int? = nil
print(name)
print(missing)

Parsing text gives an optional

The text 42 parses into a number. The text abc cannot parse, so the result is nil.

print(Int("42"))
print(Int("abc"))

Interpolation shows the wrapper

Putting an optional inside a string keeps the wrapper visible. The printed line shows Optional around the held word.

let greeting: String? = "hello"
print("Word: \(greeting)")

An optional is not a plain value

This program tries to store an optional in a plain Int variable. The compiler refuses, and the error line below is its first line.

let maybe: Int? = 5
let total: Int = maybe
print(total)

Example

var city: String? = "Paris"
var age: Int? = nil
print(city)
print(age)
print(Int("7"))
print(Int("seven"))

Key points

  • An optional wraps a value, or it wraps nil when there is no value.
  • A question mark after a type name makes that type optional.
  • An optional declared without a starting value starts as nil.
  • Turning text into a number gives an optional result.
  • Printing an optional shows the word Optional around a held value.
  • Printing an optional that holds nil shows the word nil.

In this example, the first line declares city as an optional string holding Paris. The second line declares age as an optional number holding nil. The third line prints city with its Optional wrapper. The fourth line prints age as nil. The fifth line parses the text 7 and prints Optional(7). The last line tries to parse the text seven and prints nil.

Note

An optional is not the plain value inside it, and the two cannot be mixed freely.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

What does print(Int("abc")) show?