Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue in understanding compactMap & flatMap

I have gone through from multiple tutorials that flatMap/compactMap is used to flatten an array of array but in my case it's not working or I am not understanding it properly.

let myArray = [["Raja","Kumar", nil,"Waqas"],["UAE","SINGAPORE","dUBAI","HONGKONG"]]
let final = myArray.compactMap{ $0 }

print("Result:\(final)")

OutPut:

Result:[[Optional("Raja"), Optional("Kumar"), nil, Optional("Waqas")], [Optional("UAE"), Optional("SINGAPORE"), Optional("dUBAI"), Optional("HONGKONG")]]

I tried removing nil from the above array but still it's not flattening my array.

Any help would be much appreciated.

like image 735
Muhammad Waqas Bhati Avatar asked Apr 20 '26 19:04

Muhammad Waqas Bhati


1 Answers

compactMap should be used to filter out nil elements from an array of Optionals, while flatMap can be used to flatten out a multi-dimensional array. However, you need to do both.

let final = myArray.flatMap{$0.compactMap{$0}}

print("Result:\(final)")
like image 116
Dávid Pásztor Avatar answered Apr 23 '26 00:04

Dávid Pásztor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!