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.
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)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With