Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift flatMap gives unexpected result while using with optional array

Tags:

ios

swift

flatmap

We have an array of the Person objects and each object has another array of String, which is optional. We want the consolidated list of car names in our society.

struct Person {
    let name: String
    let address: String
    let age: Int
    let income: Double
    let cars: [String]?
}
let personsArray = [Person(name:"Santosh", address: "Pune, India", age:34, income: 100000.0, cars:["i20","Swift VXI"]),
                   Person(name: "John", address:"New York, US", age: 23, income: 150000.0, cars:["Crita", "Swift VXI"]),
                   Person(name:"Amit", address:"Nagpure, India", age:17, income: 200000.0, cars:nil)]

let flatmapArray = personsArray.flatMap({$0.cars})
print(flatmapArray)

// Expected Result: ["i20", "Swift VXI", "Crita", "Swift VXI"]

// Result: [["i20", "Swift VXI"], ["Crita", "Swift VXI"]]

Why it's not giving me a single array of string as result?

I did couple of changes in the above code like my code as below, Instead of "nil", we tried to pass the empty array to the 3rd Person object.

Person(name:"Amit", address:"Nagpure, India", age:17, income: 200000.0, cars:Array())

The result was:

[["i20", "Swift VXI"], ["Crita", "Swift VXI"], []]

Still not the expected result.

If I remove the optional from the cars Array like,

let cars: [String]  
Person(name:"Amit", address:"Nagpure, India", age:17, income: 200000.0, cars:Array()) 

then it works as expected.

Result:

["i20", "Swift VXI", "Crita", "Swift VXI"]

I am not sure why it's not giving the above result if the member is of type Collection is optional?

like image 607
Santosh Botre Avatar asked Feb 04 '23 01:02

Santosh Botre


2 Answers

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 }
like image 173
zneak Avatar answered Feb 13 '23 07:02

zneak


Why let cars: [String] is different from let cars: [String]? with flatMap ?

There are two flavours of flatMap on sequences;

1) one that flattens out sequences returned from the closure passed to it,

2) one that filters out nils from the closure passed to it (note this overload is soon to be renamed to compactMap to avoid confusion as @krunal mentioned on comment)

In your code you’re using the nil filtering overload, so the nils in your array are filtered out. It won’t however do any flattening of the nested arrays. You could call flatMap again to achieve that.

like

let flatmapArray = personsArray.flatMap{$0.cars}.flatMap{$0}
print(flatmapArray)
like image 41
Prashant Tukadiya Avatar answered Feb 13 '23 06:02

Prashant Tukadiya