Since Swift 4.1 you can use compactMap:

let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5]
let actuals = possibles.compactMap { $0 }

(Swift 4.1 replaced some overloads of flatMap with compactmap. If you are interested in more detail on this then see for example: https://useyourloaf.com/blog/replacing-flatmap-with-compactmap/ )

With Swift 2 b1, you can simply do

let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5]
let actuals = possibles.flatMap { $0 }

For earlier versions, you can shim this with the following extension:

extension Array {
    func flatMap<U>(transform: Element -> U?) -> [U] {
        var result = [U]()
        result.reserveCapacity(self.count)
        for item in map(transform) {
            if let item = item {
                result.append(item)
            }
        }
        return result
    }
}

One caveat (which is also true for Swift 2) is that you might need to explicitly type the return value of the transform:

let actuals = ["a", "1"].flatMap { str -> Int? in
    if let int = str.toInt() {
        return int
    } else {
        return nil
    }
}
assert(actuals == [1])

For more info, see http://airspeedvelocity.net/2015/07/23/changes-to-the-swift-standard-library-in-2-0-betas-2-5/

Answer from Fizker on Stack Overflow
🌐
Apple Developer
developer.apple.com › documentation › swift › sequence › flatmap(_:)-jo2y
flatMap(_:) | Apple Developer Documentation
Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
🌐
Hacking with Swift
hackingwithswift.com › swift › 1.2 › flatmap
The flatMap() method transforms optionals and arrays – available from Swift 1.2
The flatMap() method is designed to allow you to transform optionals and elements inside a collection while also decreasing the amount of containment that happens.
🌐
Swift by Sundell
swiftbysundell.com › basics › map-flatmap-and-compactmap
Map, FlatMap and CompactMap | Swift by Sundell
One way of performing such value transformations is by mapping a collection of values into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap.
🌐
SwiftLee
avanderlee.com › swiftlee › swift › compactmap vs flatmap: the differences explained
CompactMap vs flatMap: The differences explained - SwiftLee
August 28, 2018 - Swift 4.1 introduced this new method with the proposal 0187: Introduce Filtermap to gain more clarity in flatMap use cases.
🌐
Swift Forums
forums.swift.org › using swift
Optional .map() vs. flatMap(): why not always use .flatMap()? - Using Swift - Swift Forums
March 24, 2021 - It seems Optional.map() when the transform closure returns nil, then result is Optional(nil) , which is same as Optional.some(nil)? Still a nil but is wrap up an optional? But Optional.flatMap() when the transform closure returns nil, the result is just nil, which is simpler.
Top answer
1 of 5
40

Since Swift 4.1 you can use compactMap:

let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5]
let actuals = possibles.compactMap { $0 }

(Swift 4.1 replaced some overloads of flatMap with compactmap. If you are interested in more detail on this then see for example: https://useyourloaf.com/blog/replacing-flatmap-with-compactmap/ )

With Swift 2 b1, you can simply do

let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5]
let actuals = possibles.flatMap { $0 }

For earlier versions, you can shim this with the following extension:

extension Array {
    func flatMap<U>(transform: Element -> U?) -> [U] {
        var result = [U]()
        result.reserveCapacity(self.count)
        for item in map(transform) {
            if let item = item {
                result.append(item)
            }
        }
        return result
    }
}

One caveat (which is also true for Swift 2) is that you might need to explicitly type the return value of the transform:

let actuals = ["a", "1"].flatMap { str -> Int? in
    if let int = str.toInt() {
        return int
    } else {
        return nil
    }
}
assert(actuals == [1])

For more info, see http://airspeedvelocity.net/2015/07/23/changes-to-the-swift-standard-library-in-2-0-betas-2-5/

2 of 5
15

I still like the first solution, which creates only one intermediate array. It can slightly more compact be written as

let filtermap = possibles.filter({ $0 != nil }).map({ $0! })

But flatMap() without type annotation and without forced unwrapping is possible:

var flatmap3 = possibles.flatMap {
    flatMap($0, { [$0] }) ?? []
}

The outer flatMap is the array method

func flatMap<U>(transform: @noescape (T) -> [U]) -> [U]

and the inner flatMap is the function

func flatMap<T, U>(x: T?, f: @noescape (T) -> U?) -> U?

Here is a simple performance comparison (compiled in Release mode). It shows that the first method is faster, approximately by a factor of 10:

let count = 1000000
let possibles : [Int?] = map(0 ..< count) { 0 : nil }

let s1 = NSDate()
let result1 = possibles.filter({ $0 != nil }).map({ $0! })
let e1 = NSDate()
println(e1.timeIntervalSinceDate(s1))
// 0.0169369578361511

let s2 = NSDate()
var result2 = possibles.flatMap {
    flatMap($0, { [$0] }) ?? []
}
let e2 = NSDate()
println(e2.timeIntervalSinceDate(s2))
// 0.117663979530334
🌐
Hacking with Swift
hackingwithswift.com › articles › 205 › whats-the-difference-between-map-flatmap-and-compactmap
What’s the difference between map(), flatMap() and compactMap()? – Hacking with Swift
October 20, 2019 - That is, either the whole thing exists or nothing exists – it flattens double optionals down to single optionals. Ultimately we don’t care about whether the outer or inner optional exists, only whether there’s a value inside there or not, which is why flatMap() is so useful.
🌐
Medium
medium.com › @smilleriosdev › advanced-swift-flatmap-ad7a38cece1e
FlatMap in the Swift Programming Language | Medium
January 21, 2025 - FlatMap is a useful function in Swift that can help you transform and flatten collections. Imagine you have a group of friends, and each of your friends has their own group of hobbies.
Find elsewhere
🌐
Better Programming
betterprogramming.pub › map-compactmap-and-flatmap-in-swift-4ea4f1a39cbd
Map, CompactMap, and FlatMap in Swift | by Alessandro Manilii | ...
February 17, 2022 - Map, CompactMap, and FlatMap in Swift How and when to use them In a normal app, it is very common to work with arrays. Often we need to take all the elements, one by one and apply some …
🌐
Donny Wals
donnywals.com › when-to-use-map-flatmap-and-compactmap
Map, flatMap and compactMap in Swift explained with examples
July 7, 2025 - Even though the type of item is [String], and we return it without changing it, we still get a flat array of strings without any nested arrays. flatMap works by first looping over your elements like a regular map does.
🌐
DeveloperMemos
developermemos.com › posts › map-flatmap-swift
Using `map` and `flatMap` in Swift | DeveloperMemos
The flatMap function in Swift is similar to map, but it also flattens the resulting collection by removing any nil values. It allows you to perform transformations that may result in optional values and automatically unwraps them.
🌐
Uraimo
uraimo.com › 2015 › 10 › 08 › Swift2-map-flatmap-demystified
Swift 3: Map and FlatMap Demystified - uraimo.com
Much has already been written about the functional aspects of Swift and how to approach problems following a more functional approach. This short article will try to give a clear and complete explanation of how map and especially flatMap work for different types in Swift 2.0 and 3.0, with ...
🌐
DhiWise
dhiwise.com › post › swift-map-vs-flatmap-solving-the-puzzle
A Comprehensive Guide to Understanding Swift Map vs. FlatMap
June 17, 2024 - When you use flatMap on an array of optional values, it removes any nil values and returns a flattened array containing only the non-optional results. This feature sets flatMap apart from the map when dealing with optional values in Swift, as it returns an array containing the results of mapping the given closure over the sequence's elements.
🌐
Mokacoding
mokacoding.com › blog › when-to-use-map-flatmap-for
When to use map, flatMap, or for loops in Swift | mokacoding
Swift allows us to natively iterate over arrays using map. Map could be used to replace every for loop in your code, but that's not a great idea. Map and for have different purposes and should be used appropriately
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › how-to-use-flatmap-with-an-optional-value
How to use flatMap() with an optional value - free Swift example code and tips
May 28, 2019 - Swift version: 5.10 · Paul Hudson @twostraws May 28th 2019 · The flatMap() method of optionals allows you to transform the optional if it has a value, or do nothing if it is empty.
🌐
Medium
medium.com › @wilson.balderrama › flatmap-method-in-action-swift-3-853a66f970bd
flatMap Method in Action — Swift 3 | by Wilson Balderrama | Medium
June 20, 2018 - when working with arrays of optional types, flatMap will map, convert the optional types to non optional, and remove the nil values. And that’s it, hope you find this article helpful. Thanks for reading me! Swift · IOS · Functional Programming · Swift3 · Arrays ·
🌐
Medium
imad-ali.medium.com › swift-map-vs-compactmap-vs-flatmap-999829b64787
Swift — Map() Vs compactMap() Vs flatMap() | by Imad Ali Mohammad | Medium
September 17, 2024 - The flatMap(_:) function does the same, and it also flattens the resulting collection.
🌐
Medium
mehrdad-ahmadian.medium.com › understanding-map-flatmap-and-compactmap-in-swift-eacafc38fb61
Understanding map, flatMap, and compactMap in Swift | by Mehrdad Ahmadian | Medium
December 24, 2023 - Understanding when and how to use map, flatMap, and compactMap can significantly enhance your Swift code's readability and efficiency. map is your go-to for simple transformations, flatMap for dealing with nested collections or optionals, and compactMap for filtering out unwanted nil values.
🌐
Swiftly
swiftly.dev › flatmap
flatMap • Swift 5.7 references for busy coders | Swiftly
flatMap 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 if the results are arrays, they are concatenated to one array.
🌐
Manning Publications
livebook.manning.com › book › swift-in-depth › chapter-10
Chapter 10. Understanding map, flatMap, and compactMap · Swift in Depth
January 30, 2019 - Mapping over arrays, dictionaries, and other collections · When and how to map over optionals · How and why to flatMap over collections · Using flatMap on optionals · Chaining and short-circuiting computations · How to mix map and flatMap for advanced transformations