0

can anyone describe this behaviour of flatMap vs compactMap? Isn't compactMap just renamed flatMap ? because I found a case where they are acting different

struct Person {
  let cars: [String]?
  let name: String
  let surname: String
  let age: Int
}

let people = [
  Person(cars: nil, name: "Adam", surname: "Bayer", age: 19),
  Person(cars: ["Audi","BMW"], name: "Michael", surname: "Knight", age: 40),
  Person(cars: ["BMW", "Mercedes", "Audi"], name: "Freddy", surname: "Krueger", age: 62)
]

let flatCars = people.flatMap { $0.cars }.flatMap { $0 }
let flatCompactCars = people.flatMap { $0.cars }.compactMap { $0 }

let compactFlatCars = people.compactMap { $0.cars }.flatMap { $0 }
let compactCars = people.compactMap { $0.cars }.compactMap { $0 }

and this is what it prints

flatMap flatMap:        ["Audi", "BMW", "BMW", "Mercedes", "Audi"]
flatMap compactMap:     [["Audi", "BMW"], ["BMW", "Mercedes", "Audi"]]
compactMap flatMap:     ["Audi", "BMW", "BMW", "Mercedes", "Audi"]
compactMap compactMap:  [["Audi", "BMW"], ["BMW", "Mercedes", "Audi"]]

can anyone tell why when I use compactMap nested array is not flatten?

Abbey Jackson
  • 885
  • 10
  • 20
Denis Kakačka
  • 697
  • 1
  • 8
  • 21
  • 3
    They have not been renamed. There are 2 because they are different. Previously it used to be ambiguous which of the 2 overloads would be used depending on if the objects were optional or not. This created a great confusion in some cases. Bottom line: NO, compact map is not just a rename of flat map but is a rename of one of the functionality that used to be in flat map. – Matic Oblak Sep 14 '18 at 11:12
  • 1
    have a look [here](https://github.com/apple/swift-evolution/blob/master/proposals/0187-introduce-filtermap.md#motivation) – ielyamani Sep 14 '18 at 11:19

1 Answers1

2

There used to be two different functions named flatMap for sequences; one to filter out nil values and one to join sequences. Now, one of these (the nil variant) has been renamed to compactMap

David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205