47

I'm trying to write an extension to Array which will allow an array of optional T's to be transformed into an array of non-optional T's.

e.g. this could be written as a free function like this:

func removeAllNils(array: [T?]) -> [T] {
    return array
        .filter({ $0 != nil })   // remove nils, still a [T?]
        .map({ $0! })            // convert each element from a T? to a T
}

But, I can't get this to work as an extension. I'm trying to tell the compiler that the extension only applies to Arrays of optional values. This is what I have so far:

extension Array {
    func filterNils<U, T: Optional<U>>() -> [U] {
        return filter({ $0 != nil }).map({ $0! })
    }
}

(it doesn't compile!)

7 Answers 7

80

As of Swift 2.0, you don't need to write your own extension to filter nil values from an Array, you can use flatMap, which flattens the Array and filters nils:

let optionals : [String?] = ["a", "b", nil, "d"]
let nonOptionals = optionals.flatMap{$0}
print(nonOptionals)

Prints:

[a, b, d]

Note:

There are 2 flatMap functions:

5
  • The only bad thing (minor) is it's Complexity: O(M + N) instead of O(N). Looks like internally flatMap is a "conjunction" of map and filter instead of slightly faster 1-loop own implementation. But for this question it's not a problem
    – zxcat
    Mar 9, 2016 at 23:20
  • @zxcat What's M and N?
    – kostek
    Apr 13, 2016 at 17:26
  • 2
    @kostek, here is a quote from flatMap implementation: - Complexity: O(M + N), where M is the length of self and N is the length of the result.
    – zxcat
    Apr 13, 2016 at 20:59
  • 1
    Although flatMap can be used most of the time, it's actually a much more powerful function which can lead to unintended consequences. I would recommend using removeNils instead.
    – Senseful
    Jul 24, 2016 at 2:11
  • There are 2 flatMap functions (overloaded), one is to return concatenated results and the other is to return non-nil values. Refer - developer.apple.com/documentation/swift/sequence/… Aug 13, 2017 at 4:54
65

TL;DR

Swift 4

Use array.compactMap { $0 }. Apple updated the framework so that it'll no longer cause bugs/confusion.

Swift 3

To avoid potential bugs/confusion, don't use array.flatMap { $0 } to remove nils; use an extension method such as array.removeNils() instead (implementation below, updated for Swift 3.0).


Although array.flatMap { $0 } works most of the time, there are several reasons to favor an array.removeNils() extension:

  • removeNils describes exactly what you want to do: remove nil values. Someone not familiar with flatMap would need to look it up, and, when they do look it up, if they pay close attention, they'll come to the same conclusion as my next point;
  • flatMap has two different implementations which do two entirely different things. Based off of type-checking, the compiler is going to decide which one is invoked. This can be very problematic in Swift, since type-inference is used heavily. (E.g. to determine the actual type of a variable, you may need to inspect multiple files.) A refactor could cause your app to invoke the wrong version of flatMap which could lead to difficult-to-find bugs.
  • Since there are two completely different functions, it makes understanding flatMap much more difficult since you can easily conflate the two.
  • flatMap can be called on non-optional arrays (e.g. [Int]), so if you refactor an array from [Int?] to [Int] you may accidentally leave behind flatMap { $0 } calls which the compiler won't warn you about. At best it'll simply return itself, at worst it'll cause the other implementation to be executed, potentially leading to bugs.
  • In Swift 3, if you don't explicitly cast the return type, the compiler will choose the wrong version, which causes unintended consequences. (See Swift 3 section below)
  • Finally, it slows down the compiler because the type-checking system needs to determine which of the overloaded functions to call.

To recap, there are two versions of the function in question both, unfortunately, named flatMap.

  1. Flatten sequences by removing a nesting level (e.g. [[1, 2], [3]] -> [1, 2, 3])

    public struct Array<Element> : RandomAccessCollection, MutableCollection {
        /// Returns an array containing the concatenated results of calling the
        /// given transformation with each element of this sequence.
        ///
        /// Use this method to receive a single-level collection when your
        /// transformation produces a sequence or collection for each element.
        ///
        /// In this example, note the difference in the result of using `map` and
        /// `flatMap` with a transformation that returns an array.
        ///
        ///     let numbers = [1, 2, 3, 4]
        ///
        ///     let mapped = numbers.map { Array(count: $0, repeatedValue: $0) }
        ///     // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
        ///
        ///     let flatMapped = numbers.flatMap { Array(count: $0, repeatedValue: $0) }
        ///     // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
        ///
        /// In fact, `s.flatMap(transform)`  is equivalent to
        /// `Array(s.map(transform).joined())`.
        ///
        /// - Parameter transform: A closure that accepts an element of this
        ///   sequence as its argument and returns a sequence or collection.
        /// - Returns: The resulting flattened array.
        ///
        /// - Complexity: O(*m* + *n*), where *m* is the length of this sequence
        ///   and *n* is the length of the result.
        /// - SeeAlso: `joined()`, `map(_:)`
        public func flatMap<SegmentOfResult : Sequence>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element]
    }
    
  2. Remove elements from a sequence (e.g. [1, nil, 3] -> [1, 3])

    public struct Array<Element> : RandomAccessCollection, MutableCollection {
        /// Returns an array containing the non-`nil` results of calling the given
        /// transformation with each element of this sequence.
        ///
        /// Use this method to receive an array of nonoptional values when your
        /// transformation produces an optional value.
        ///
        /// In this example, note the difference in the result of using `map` and
        /// `flatMap` with a transformation that returns an optional `Int` value.
        ///
        ///     let possibleNumbers = ["1", "2", "three", "///4///", "5"]
        ///
        ///     let mapped: [Int?] = numbers.map { str in Int(str) }
        ///     // [1, 2, nil, nil, 5]
        ///
        ///     let flatMapped: [Int] = numbers.flatMap { str in Int(str) }
        ///     // [1, 2, 5]
        ///
        /// - Parameter transform: A closure that accepts an element of this
        ///   sequence as its argument and returns an optional value.
        /// - Returns: An array of the non-`nil` results of calling `transform`
        ///   with each element of the sequence.
        ///
        /// - Complexity: O(*m* + *n*), where *m* is the length of this sequence
        ///   and *n* is the length of the result.
        public func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
    }
    

#2 is the one that people use to remove nils by passing { $0 } as transform. This works since the method performs a map, then filters out all nil elements.

You may be wondering "Why did Apple not rename #2 to removeNils()"? One thing to keep in mind is that using flatMap to remove nils is not the only usage of #2. In fact, since both versions take in a transform function, they can be much more powerful than those examples above.

For example, #1 could easily split an array of strings into individual characters (flatten) and capitalize each letter (map):

["abc", "d"].flatMap { $0.uppercaseString.characters } == ["A", "B", "C", "D"]

While number #2 could easily remove all even numbers (flatten) and multiply each number by -1 (map):

[1, 2, 3, 4, 5, 6].flatMap { ($0 % 2 == 0) ? nil : -$0 } == [-1, -3, -5]

(Note that this last example can cause Xcode 7.3 to spin for a very long time because there are no explicit types stated. Further proof as to why the methods should have different names.)

The real danger of blindly using flatMap { $0 } to remove nils comes not when you call it on [1, 2], but rather when you call it on something like [[1], [2]]. In the former case, it'll call invocation #2 harmlessly and return [1, 2]. In the latter case, you may think it would do the same (harmlessly return [[1], [2]] since there are no nil values), but it will actually return [1, 2] since it's using invocation #1.

The fact that flatMap { $0 } is used to remove nils seems to be more of Swift community recommendation rather than one coming from Apple. Perhaps if Apple notices this trend, they'll eventually provide a removeNils() function or something similar.

Until then, we're left with coming up with our own solution.


Solution

// Updated for Swift 3.0
protocol OptionalType {
    associatedtype Wrapped
    func map<U>(_ f: (Wrapped) throws -> U) rethrows -> U?
}

extension Optional: OptionalType {}

extension Sequence where Iterator.Element: OptionalType {
    func removeNils() -> [Iterator.Element.Wrapped] {
        var result: [Iterator.Element.Wrapped] = []
        for element in self {
            if let element = element.map({ $0 }) {
                result.append(element)
            }
        }
        return result
    }
}

(Note: Don't get confused with element.map... it has nothing to do with the flatMap discussed in this post. It's using Optional's map function to get an optional type that can be unwrapped. If you omit this part, you'll get this syntax error: "error: initializer for conditional binding must have Optional type, not 'Self.Generator.Element'." For more information about how map() helps us, see this answer I wrote about adding an extension method on SequenceType to count non-nils.)

Usage

let a: [Int?] = [1, nil, 3]
a.removeNils() == [1, 3]

Example

var myArray: [Int?] = [1, nil, 2]
assert(myArray.flatMap { $0 } == [1, 2], "Flat map works great when it's acting on an array of optionals.")
assert(myArray.removeNils() == [1, 2])

var myOtherArray: [Int] = [1, 2]
assert(myOtherArray.flatMap { $0 } == [1, 2], "However, it can still be invoked on non-optional arrays.")
assert(myOtherArray.removeNils() == [1, 2]) // syntax error: type 'Int' does not conform to protocol 'OptionalType'

var myBenignArray: [[Int]?] = [[1], [2, 3], [4]]
assert(myBenignArray.flatMap { $0 } == [[1], [2, 3], [4]], "Which can be dangerous when used on nested SequenceTypes such as arrays.")
assert(myBenignArray.removeNils() == [[1], [2, 3], [4]])

var myDangerousArray: [[Int]] = [[1], [2, 3], [4]]
assert(myDangerousArray.flatMap { $0 } == [1, 2, 3, 4], "If you forget a single '?' from the type, you'll get a completely different function invocation.")
assert(myDangerousArray.removeNils() == [[1], [2, 3], [4]]) // syntax error: type '[Int]' does not conform to protocol 'OptionalType'

(Notice how on the last one, flatMap returns [1, 2, 3, 4] while removeNils() would have been expected to return [[1], [2, 3], [4]].)


The solution is similar to the answer @fabb linked to.

However, I made a few modifications:

  • I didn't name the method flatten, since there is already a flatten method for sequence types, and giving the same name to entirely different methods is what got us in this mess in the first place. Not to mention that it's much easier to misinterpret what flatten does than it is removeNils.
  • Rather than creating a new type T on OptionalType, it uses the same name that Optional uses (Wrapped).
  • Instead of performing map{}.filter{}.map{}, which leads to O(M + N) time, I loop through the array once.
  • Instead of using flatMap to go from Generator.Element to Generator.Element.Wrapped?, I use map. There's no need to return nil values inside the map function, so map will suffice. By avoiding the flatMap function, it's harder to conflate yet another (i.e. 3rd) method with the same name which has an entirely different function.

The one drawback to using removeNils vs. flatMap is that the type-checker may need a bit more hinting:

[1, nil, 3].flatMap { $0 } // works
[1, nil, 3].removeNils() // syntax error: type of expression is ambiguous without more context

// but it's not all bad, since flatMap can have similar problems when a variable is used:
let a = [1, nil, 3] // syntax error: type of expression is ambiguous without more context
a.flatMap { $0 }
a.removeNils()

I haven't looked into it much, but it seems you can add:

extension SequenceType {
  func removeNils() -> Self {
    return self
  }
}

if you want to be able to call the method on arrays that contain non-optional elements. This could make a massive rename (e.g. flatMap { $0 } -> removeNils()) easier.


Assigning to self is different than assigning to a new variable?!

Take a look at the following code:

var a: [String?] = [nil, nil]

var b = a.flatMap{$0}
b // == []

a = a.flatMap{$0}
a // == [nil, nil]

Surprisingly, a = a.flatMap { $0 } does not remove nils when you assign it to a, but it does remove nils when you assign it to b! My guess is that this has something to do with the overloaded flatMap and Swift choosing the one we didn't mean to use.

You could temporarily resolve the problem by casting it to the expected type:

a = a.flatMap { $0 } as [String]
a // == []

But this can be easy to forget. Instead, I would recommend using the removeNils() method above.


Update

Seems like there's a proposal to deprecate at least one of the (3) overloads of flatMap: https://github.com/apple/swift-evolution/blob/master/proposals/0187-introduce-filtermap.md

6
  • I highly disagree with the part Will lead to bugs. Yeah sure it is undefined behavior when you suddenly change [Int?] to [Int]... but as you mentioned type-inference will detects types automatically... The ONLY case that this will be a bug, is where .flatMap is the last line of your code (like your unit-tests) which means, it was not needed to begin with. because you will use it's result somewhere! in UI, bind to some other variable, return from a method... and compiler will catch that error there... Apr 23, 2017 at 8:35
  • But i do agree this part was really confusing: a = a.flatMap{$0} a // == [nil, nil] Apr 23, 2017 at 8:39
  • The reason why a remains [nil, nil], is because a is still of type [Int?]. In which nils are valid. May 5, 2017 at 13:33
  • 1
    This solution does no longer work in Swift 4, I have not yet got it to work. Any clue?
    – Sajjon
    Jun 18, 2017 at 10:07
  • 1
    There's an accepted proposal for Swift 5: compactMap to remove nils from an array of optionals. It also references a new Sequence.compact() but I can't find the proposal for that Dec 23, 2017 at 4:49
44

It's not possible to restrict the type defined for a generic struct or class - the array is designed to work with any type, so you cannot add a method that works for a subset of types. Type constraints can only be specified when declaring the generic type

The only way to achieve what you need is by creating either a global function or a static method - in the latter case:

extension Array {
    static func filterNils(_ array: [Element?]) -> [Element] {
        return array.filter { $0 != nil }.map { $0! }
    }
}

var array:[Int?] = [1, nil, 2, 3, nil]

Array.filterNils(array)

Or simply use compactMap (previously flatMap), which can be used to remove all nil values:

[1, 2, nil, 4].compactMap { $0 } // Returns [1, 2, 4]
4
  • Fair enough, now that I think about it that makes sense - I was just thinking that it would make that particular method only available to Optional types, but of course it would try to apply to all of them. So I guess I'll be doing what you suggested then, or creating a free function outside of the Array class!
    – Javawag
    Jan 28, 2015 at 12:28
  • 4
    .flatMap does exactly the same, but you don't need to write an extension. You really should update your answer to reflect that. Feb 10, 2017 at 18:45
  • From swift 4, flatMap is deprecated. We can use compactMap instead of flatMap May 19, 2018 at 13:35
  • 1
    @Antonio I ended up making this: func filterNils<T>() -> [T] where Element == T? { self.compactMap { $0 } }
    – Sentry.co
    Jul 15, 2020 at 12:43
12

Since Swift 2.0 it is possible to add a method that works for a subset of types by using where clauses. As discussed in this Apple Forum Thread this can be used to filter out nil values of an array. Credits go to @nnnnnnnn and @SteveMcQwark.

As where clauses do not yet support generics (like Optional<T>), a workaround is necessary via a Protocol.

protocol OptionalType {  
    typealias T  
    func intoOptional() -> T?  
}  

extension Optional : OptionalType {  
    func intoOptional() -> T? {  
        return self.flatMap {$0}  
    }  
}  

extension SequenceType where Generator.Element: OptionalType {  
    func flatten() -> [Generator.Element.T] {  
        return self.map { $0.intoOptional() }  
            .filter { $0 != nil }  
            .map { $0! }  
    }  
}  

let mixed: [AnyObject?] = [1, "", nil, 3, nil, 4]  
let nonnils = mixed.flatten()    // 1, "", 3, 4  
4
  • With the final version of Swift, the anser of @Chris Trevarthen is much more simple. The only plus this solution has, is that flatten cannot be called on an array that already does not contain any optionals.
    – fabb
    Nov 9, 2015 at 10:38
  • ...and that it's more elegant to write just flatten() than flatMap{$0}... but I agree that it's a bit too much code just for this... btw why you don't use flatMap in the extension instead of filter and map?
    – User
    Aug 29, 2016 at 14:21
  • As far as I remember, flatMap was added to Optionals only after 2.0, my answer is older than that
    – fabb
    Aug 29, 2016 at 14:25
  • Actually it isn't that much code considering that OptionalType is also useful for other things, like stackoverflow.com/questions/33138712/… this is preferable over writing flatMap{$0} each time.
    – User
    Aug 30, 2016 at 10:41
12

Swift 4

If you are fortunate enough to be using Swift 4 then you can filter out nil values using compactMap

array = array.compactMap { $0 }

E.g.

let array = [1, 2, nil, 4]
let nonNilArray = array.compactMap { $0 }

print(nonNilArray)
// [1, 2, 4]
1
  • 2
    This should be the approved answer.
    – masty
    Jun 26, 2018 at 22:49
6

Swift 4

This works with Swift 4:

protocol OptionalType {
    associatedtype Wrapped
    var optional: Wrapped? { get }
}

extension Optional: OptionalType {
    var optional: Wrapped? { return self }
}

extension Sequence where Iterator.Element: OptionalType {
    func removeNils() -> [Iterator.Element.Wrapped] {
        return self.flatMap { $0.optional }
    }
}

Test:

class UtilitiesTests: XCTestCase {
    
    func testRemoveNils() {
        let optionalString: String? = nil
        let strings: [String?] = ["Foo", optionalString, "Bar", optionalString, "Baz"]
        XCTAssert(strings.count == 5)
        XCTAssert(strings.removeNils().count == 3)
        let integers: [Int?] = [2, nil, 4, nil, nil, 5]
        XCTAssert(integers.count == 6)
        XCTAssert(integers.removeNils().count == 3)
    }
}
1

Solution for Swift 5.3 and beyond

extension Array where Element == Any? {
   /**
    * Remove optionals from array
    * ## Examples:
    * Array.filterNils([2,nil,1,0]) // [2,1,0]
    * let someArr: [Int?] = [2,nil,1,0]
    * Array.filterNils(someArr) // [2,1,0]
    */
   static func filterNils<T>(_ array: [T?]) -> [T] {
      return array.compactMap { $0 }
   }
}
2
  • Why do you need to define where Element == Any? if the function is static anyways?
    – Ferdz
    May 14, 2021 at 18:43
  • Good question. I think it was non-static. And then I moved to static and didn't change the clause.
    – Sentry.co
    May 19, 2021 at 2:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.