Swift Language Filtering out nil from an Array transformation with flatMap(_:)


Example

You 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, you can this in order to transform a [String] into a [Int] using Int's failable String initializer, filtering out any elements that cannot be converted:

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]