3

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
Muhammad Waqas Bhati
  • 2,775
  • 20
  • 25
  • 1
    Here in short: `compactMap` filters all `nil` values from an array, `flatMap` turns an array of arrays into a single array by pulling all values from the nested arrays into a single one. – LinusGeffarth Apr 03 '19 at 11:19

3 Answers3

5

.compactMap

...is used to produce a list without optional objects, you need to use compactMap on the inner array where you got nils, like so:

let result = myArray.map { $0.compactMap { $0 } }

Result: [["Raja", "Kumar", "Waqas"], ["UAE", "SINGAPORE", "dUBAI", "HONGKONG"]]


.flatmap

...is used to flatten a collection of collections, for example

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

Result: ["Raja", "Kumar", "Waqas", "UAE", "SINGAPORE", "dUBAI", "HONGKONG"]

Community
  • 1
  • 1
AamirR
  • 11,672
  • 4
  • 59
  • 73
5

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)")
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
3

Please read the documentation

map(_:)

Returns an array containing the results of mapping the given closure over the sequence’s elements.

compactMap(_:)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

flatMap(_:)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

Each Discussion section contains an example.

vadian
  • 274,689
  • 30
  • 353
  • 361