2

I have Array A of objects of type struct

struct Caste {
    var arr = [1,2]
}

let siri =  [Caste(), Caste(), Caste()]

Now I want a single array in which all elements of each objects array consist as shown below:

let re1 = siri.compactMap { $0.arr }
print("COMPACT: \(re1)")
let re2 = siri.flatMap { $0.arr }
print("FLAT: \(re2)")

Result:

COMPACT: [[1, 2], [1, 2], [1, 2]] FLAT: [1, 2, 1, 2, 1, 2]

As flatMap is deprecated in Swift 4.1 I tried with compactMap but it is giving array of array not a single array.

How can I achieve via compactMap as I'm getting via flatMap.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Abhishek Thapliyal
  • 3,497
  • 6
  • 30
  • 69
  • 2
    That usage case of `flatmap` is not deprecated – ielyamani Nov 26 '18 at 18:17
  • One thing that the other answer doesn't cover very clearly. In the snippet `siri.compactMap { $0.arr }`, since the closure is expected to be of type `(T) -> T?`, and since Swift implicitly promote a value t of type `T` into an optional of type `T?`, what is actually returned is `Optional($0.arr)` – Alexander Nov 26 '18 at 18:45

1 Answers1

1

flatMap was split up into itself and compactMap. flatMap is to flatten an array while the purpose of compactMap is to take an array of [T?] and remove all nil objects making an array of [T]. This has a count of <= the original count depending on the number of nils.

Frederik Winkelsdorf
  • 4,383
  • 1
  • 34
  • 42
Sethmr
  • 3,046
  • 1
  • 24
  • 42
  • To be more precise, there's a distinction to be made between `Any` (a protocol type) and `T` (a placeholder for a specific type) – Alexander Nov 26 '18 at 18:32