Filtering out nil from an Array transformation with flatMap
suggest changeYou can use flatMap(_:) in a similar manner to map(_:) in order to create an array by applying a transform to a sequence’s elements.
extension SequenceType {
public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
}
The difference with this version of flatMap(_:) is that it expects the transform closure to return an Optional value T? for each of the elements. It will then safely unwrap each of these optional values, filtering out nil – resulting in an array of [T].
For example, use it to transform a [String] into an [Int] with Int's failable String initializer, dropping elements that cannot be converted. Swift 4.1 renamed this optional-filtering overload to compactMap. The signature above is Swift 2 (SequenceType, @noescape).
let strings = ["1", "foo", "3", "4", "bar", "6"]
let numbersThatCanBeConverted = strings.flatMap { Int($0) }
print(numbersThatCanBeConverted) // [1, 3, 4, 6]
You can also use flatMap(_:)’s ability to filter out nil in order to simply convert an array of optionals into an array of non-optionals:
let optionalNumbers : [Int?] = [nil, 1, nil, 2, nil, 3]
let numbers = optionalNumbers.flatMap { $0 }
print(numbers) // [1, 2, 3]