A global flatMap
function has been added for both optionals and sequences, and flatMap
methods have been added to the optional and array types, much to the joy of functional-leaning Swifters everywhere. For sequences and arrays, this provides a way to map each element to an array, with the resulting array of arrays flattened back to an array of their joined elements:
let numbers = [1, 2, 3, 4]
let expanded = numbers.flatMap { Array(count: $0, repeatedValue: $0) }
// flatMap flattens the result:
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
let nested = numbers.map { Array(count: 0, repeatedValue: $0) }
// with map, you end up with a nested array:
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
For optionals, flatMap
lets you safely call functions that don’t take an optional value without going through an optional binding:
let squareRootOfLast = expanded.last.flatMap { sqrt(Double($0)) }
// Optional(2.0)