Sobes.tech
Junior — Middle

Explain the working principle of the Flat Map method and how it differs from the regular Map when processing data collections.

sobes.tech AI

Answer from AI

The map method transforms each element of a collection by applying a function and returns an array of the results. If the function returns a collection, the result will be an array of collections.

flatMap first applies the function to each element like map, but then "flattens" (flattens) the nested collections into a single flat array.

Example:

let numbers = [1, 2, 3]

// map with a function returning an array
let mapped = numbers.map { Array(repeating: $0, count: $0) }
// mapped = [[1], [2, 2], [3, 3, 3]]

// flatMap with the same function
let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// flatMapped = [1, 2, 2, 3, 3, 3]

Thus, flatMap is useful when the function returns a collection and you want to obtain a single flat array without nested arrays.

Explain the working principle of the Flat Map method… - sobes.tech