9

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?

2
  • 2
    FYI: flatMap is Deprecated, Use compactMap Commented Feb 15, 2018 at 6:30
  • 3
    @Krunal, to be clear, this is in the upcoming version of Swift, and only available currently if you use the Xcode beta. Commented Feb 15, 2018 at 6:34

3 Answers 3

8

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

Of course. If you feel that this adequately answered your question, don't forget to click the checkmark underneath the score.
3

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)

8 Comments

Nope it doesn't explain that fact that why let cars: [String] is working and let cars: [String]? not.
If you remove the optional/'?' then it works perfectly fine. The @zneak answer seems correct to me.
@SantoshBotre Then what you get why [String] is working and String]? not. ? i edited answer and remove that first line
@SantoshBotre Check now the why factor.
@Mr.Bista Check now why factor
|
0

You need to call flatMap once more for array containing Optionals: personsArray.flatMap { $0.cars }.flatMap { $0 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.