CompactMap
compactMap()
works the same as map()
but returns only the non-nil results.
var strings: [String] = ["1", "2", "three", "4"]
let numbers: [Int] = strings.compactMap { Int($0) } // [1, 2, 4]
In this example, we use the Int
initializer that tries to convert a String
to an integer, if it fails, it returns nil
. So with compactMap
, we'll only get the numbers that were successfully converted.
FlatMap
flatMap
converts a multi-dimensional array into a single-dimensional array. A multi-dimensional array is an array of arrays, also known as a matrix.
let matrix: [[Int]] = [
[2, 2],
[3, 3, 3],
[4, 4, 4, 4],
]
let array = matrix.flatMap { $0 } // [2, 2, 3, 3, 3, 4, 4, 4, 4]
Map on Optionals
We can use the map()
function on an Optional
variable to apply a transformation to its wrapped value if it's not nil
. Otherwise, the function returns nil
.
var nameNil: String? = nil
var nameNotNil: String? = "Pablo"
let nameNilResult = nameNil.map { $0.uppercased() } // nil
let nameNotNilResult = nameNotNil.map { $0.uppercased() } // PABLO
Map on Optionals vs Map on Arrays
It's common to confuse the map()
applied to an Optional
with the one applied to the wrapped value of an Optional
. Let's see both examples.
let optionalArray: [Int]? = [1, 2, 3]
let resultSquares = optionalArray?.map { $0 * $0 } // [1, 4, 9]
let resultCount = optionalArray.map { $0.count } // 3
In the first example, using the ?
symbol, we access the wrapped value of optionalArray
, which, being an array, allows us to apply map()
. In the second example, we apply map()
to the Optional
itself, so $0
will be the entire array.
Be the first to comment