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?