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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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]


Got any Swift Language Question?