compactMap
compactMap is a functional method that returns an array that contains the results of mapping a given closure over the elements of a sequence, with the exception that nil
results are filtered out. Similar methods are map and flatMap.
compactMap
over array of Strings
Here, Int()
is an initializer that returns an optional Int
: an Int
if the string can be converted to one, and nil
otherwise. Importantly, the resulting array is of type [Int]
(not [Int?]
).
let numberStrings = ["1", "2", "3", "four"]
let numbers = numberStrings.compactMap { Int($0) }
print(numbers) // [1, 2, 3]
For reference, here is what would happen if we used map with this example instead:
let numberStrings = ["1", "2", "3", "four"]
let numbers = numberStrings.map { Int($0) }
print(numbers) // [Optional(1), Optional(2), Optional(3), nil]