๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Optional Mapping

Optional mapping is changing the value inside an optional without taking the optional away. The result stays optional, so a fallback can settle it later.

Map changes a held value

The closure triples the held score. The result stays optional, so the print settles it with a fallback.

let score: Int? = 4
let tripled = score.map { $0 * 3 }
print(tripled ?? 0)

Map on nil stays nil

The optional holds nil, so the closure never runs. The fallback in the print shows that no value arrived.

let missing: Int? = nil
let tripled = missing.map { $0 * 3 }
print(tripled ?? -1)

FlatMap parses text into a number

The closure returns an optional number from each piece of text. The word ten cannot become a number, so its result is nil and the fallback prints.

let good: String? = "42"
let bad: String? = "ten"
let goodNumber = good.flatMap { Int($0) }
let badNumber = bad.flatMap { Int($0) }
print(goodNumber ?? 0)
print(badNumber ?? -1)

Map then a fallback on one line

Each name passes through map before the fallback settles the line. The held name prints in capitals and the missing name prints the fallback.

let name: String? = "ana"
let missing: String? = nil
print(name.map { $0.uppercased() } ?? "UNKNOWN")
print(missing.map { $0.uppercased() } ?? "UNKNOWN")

Example

let priceText: String? = "15"
let number = priceText.flatMap { Int($0) }
let doubled = number.map { $0 * 2 }
print(doubled ?? 0)
let missing: String? = nil
print(missing.flatMap { Int($0) } ?? -1)

Key points

  • map changes a held value with a closure and keeps the result optional.
  • map on nil gives nil and the closure never runs.
  • flatMap uses a closure that itself returns an optional value.
  • flatMap gives a single optional result rather than an optional inside an optional.
  • Parsing text inside flatMap gives nil when the text is not a valid number.
  • A mapped result can settle with ?? on the same line.

In this example, flatMap parses the held text 15 into the number 15. The map call then doubles that number to 30. The first print settles the optional result and shows 30. The missing optional holds nil, so its flatMap gives nil. The last print settles that result with the fallback and shows -1.

Note

Printing through ?? or if let keeps the plain value on screen.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A program sets value to the optional number 5. What does printing value.map { $0 + 1 } ?? 0 give?