How to Use Swift Flatmap to Filter Out Optionals from an Array

How to use swift flatMap to filter out optionals from an array

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/

Swift flatMap on array with elements are optional has different behavior

As @Adam says, it's due to the explicit type that you're supplying for your result. In your second example, this is leading to confusion caused by double wrapped optionals. To better understand the problem, let's take a look at the flatMap function signature.

@warn_unused_result
public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]

When you explicitly specify that the result is of type [Int?], because flatMap returns the generic type [T] – Swift will infer T to be Int?.

Now this causes confusion because the closure that your pass to flatMap takes an element input and returns T?. Because T is Int?, this closure is now going to be returning T?? (a double wrapped optional). This compiles fine because types can be freely promoted to optionals, including optionals being promoted to double optionals.

So what's happening is that your Int? elements in the array are getting promoted to Int?? elements, and then flatMap is unwrapping them back down to Int?. This means that nil elements can't get filtered out from your arr1 as they're getting doubly wrapped, and flatMap is only operating on the second layer of wrapping.

Why arr2 is able to have nil filtered out of it appears to be as a result of the promotion of the closure that you pass to flatMap. Because you explicitly annotate the return type of the closure to be Int?, the closure will get implicitly promoted from (Element) -> Int? to (Element) -> Int?? (closure return types can get freely promoted in the same way as other types) – rather than the element itself being promoted from Int? to Int??, as without the type annotation the closure would be inferred to be (Element) -> Int??.

This quirk appears to allow nil to avoid being double wrapped, and therefore allowing flatMap to filter it out (not entirely sure if this is expected behaviour or not).

You can see this behaviour in the example below:

func optionalIntArrayWithElement(closure: () -> Int??) -> [Int?] {
let c = closure() // of type Int??
if let c = c { // of type Int?
return [c]
} else {
return []
}
}

// another quirk: if you don't explicitly define the type of the optional (i.e write 'nil'),
// then nil won't get double wrapped in either circumstance
let elementA : () -> Int? = {Optional<Int>.None} // () -> Int?
let elementB : () -> Int?? = {Optional<Int>.None} // () -> Int??

// (1) nil gets picked up by the if let, as the closure gets implicitly upcast from () -> Int? to () -> Int??
let arr = optionalIntArrayWithElement(elementA)

// (2) nil doesn't get picked up by the if let as the element itself gets promoted to a double wrapped optional
let arr2 = optionalIntArrayWithElement(elementB)

if arr.isEmpty {
print("nil was filtered out of arr") // this prints
}

if arr2.isEmpty {
print("nil was filtered out of arr2") // this doesn't print
}

Moral of the story

Steer away from double wrapped optionals, they can give you super confusing behaviour!

If you're using flatMap, then you should be expecting to get back [Int] if you pass in [Int?]. If you want to keep the optionality of the elements, then use map instead.

Swift flatMap gives unexpected result while using with optional array

The issue is that for the purposes of map and flatMap, optionals are collections of 0 or 1 elements. You can directly call map and flatMap on optionals without unwrapping them:

let foo: Int? = 5
foo.map { $0 * $0 } // Int? = 25; "collection of one element"
let bar: Int? = nil
bar.map { $0 * $0 } // Int? = nil; "collection of zero elements"

To illustrate in more familiar terms your current situation, you're looking at the equivalent of this:

class Person {
let cars: [[String]]
}

If you had a var persons: [Person] and called persons.flatMap { $0.cars }, the resulting type of this operation would unquestionably be [[String]]: you start out with three layers of collections and you end up with two.

This is also effectively what is happening with [String]? instead of [[String]].

In the case that you are describing, I would advise dropping the optional and using empty arrays. I'm not sure that the distinction between a nil array and an empty array is truly necessary in your case: my interpretation is that a nil array means that the person is incapable of owning a car, whereas an empty array means that the person is capable of owning a car but doesn't have any.

If you cannot drop the optional, then you will need to call flatMap twice to flatten two layers instead of only one:

persons.flatMap { $0.cars }.flatMap { $0 }

Swift: shortcut unwrapping of array of optionals

This solution will get you a new array with all values unwrapped and all nil's filtered away.

Swift 4.1:

let arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"]
let arrayWithNoOptionals = arrayOfOptionals.compactMap { $0 }

Swift 2.0:

let arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"]
let arrayWithNoOptionals = arrayOfOptionals.flatMap { $0 }

Swift 1.0:

let arrayOfOptionals: [String?] = ["Seems", "like", "an", nil, "of", "optionals"]
let arrayWithNoOptionals = arrayOfOptionals.filter { $0 != nil }.map { $0! }

Swift 3 use optional chaining in map or filter

You should use flatMap (compactMap in Swift 4) to filter out nils:

let sectionNames = pois.flatMap { $0.IconName }

Creating an extension to filter nils from an Array in Swift

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]

flatMap is not removing nil objects from array

You shouldn't have it in the []. Instead try:

let inventoryBooks = Books.books(fromDictArray: arrayOfBooks).flatMap{$0}

Having it is the [] is making an array with one item in it, the result of the fromDictArray call. So it's structured like [[1, 2, 3]] instead of [1, 2, 3]. So when you call flatmap it checks that one item, which that isn't nil, and returns it.

Is there a built-in function to map over non-nil elements, and remove nil elements of array?

You can use compactMap (which will remove nil values) in conjunction with flatMap of the Optional (which will call the closure only if the optional is not nil, and just return nil otherwise), e.g.

let values: [Int?] = [1, 2, nil, 4]
let results = values.compactMap { $0.flatMap { $0 * 2 } }

Resulting in:

[2, 4, 8]



Related Topics



Leave a reply



Submit