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.
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)