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?