Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Optional Map & FlatMap
Written by Team Kodeco

In Swift, the map and flatMap functions are commonly used to transform and flatten non-optional values. However, these functions can also be used with optional values.

Optional Map

The map function can be used to transform the value of an optional if it isn’t nil. The following code demonstrates an example of using the map function with an optional integer:

var optionalInt: Int? = 5
var mappedInt: Int? = optionalInt.map { $0 * 2 }
print(mappedInt) // Output: Optional(10)

optionalInt = nil
mappedInt = optionalInt.map { $0 * 2 }
print(mappedInt) // nil

In this example, the map function takes a closure that multiplies the optional integer by 2 (if it is not nil).

Optional FlatMap

The flatMap function can be used to flatten a nested optional. The following code demonstrates an example of using the flatMap function with nested optional integers:

let nestedOptional: Int?? = Optional(Optional(5))
let flatMappedOptional = nestedOptional.flatMap { $0 }
print(flatMappedOptional) // Output: Optional(5)

In this example, the flatMap function takes a closure that returns the nested optional integer, and returns a new optional integer with a value of 5.

It’s important to note that if the value inside the outer optional is nil, the flatMap will return nil.

© 2024 Kodeco Inc.