Swift Tutorial · Swift Basics · Lesson 10 of 30

Swift Optionals

Represent missing values with optionals and unwrap them safely with if let, guard let, ?? and optional chaining.

Create a free account to save this page, take notes and track your progress. Sign in

Optional types

A normal type can never be nil. String? is an optional: either a String or nil. You must unwrap it before use.

  • if let name { } / guard let name else { } unwrap into a non-optional constant.
  • ?? provides a default value.
  • ?. (optional chaining) calls only when the value exists.
  • ! force-unwraps and crashes on nil; avoid it.
Unwrapping optionals
struct User {
    let name: String
    let email: String?
}

let users = [User(name: "Ana", email: "[email protected]"), User(name: "Ben", email: nil)]
for user in users {
    print("\(user.name): \(user.email?.uppercased() ?? "(none)")")
    if let email = user.email {
        print("  send welcome mail to \(email)")
    }
}
var nickname: String? = nil
print(nickname?.count as Any)
nickname = "Ana"
if let nickname { print(nickname.count) }

Output

Ana: [email protected]
  send welcome mail to [email protected]
Ben: (none)
nil
3

Run this on your computer — see “Get Started” for setup.

Optional map and compactMap

map transforms an optional's value if there is one; compactMap on a collection drops the nil results.

map and compactMap with optionals
let inputs = ["3", "abc", "10", ""]
let numbers = inputs.compactMap { Int($0) }
print(numbers)

let first: String? = inputs.first
let length = first.map { $0.count }
print(length as Any)
let missing: String? = nil
print(missing.map { $0.count } ?? -1)

Output

[3, 10]
Optional(1)
-1

Run this on your computer — see “Get Started” for setup.

Test yourself

What does a ?? b return when a is nil?

  1. nil
  2. b
  3. It crashes
  4. false
Show answer

Answer: b

Was this page helpful?