Sobes.tech
Junior — Middle

Can you explain the difference between flatMap and compactMap in programming languages?

sobes.tech AI

Answer from AI

In programming languages like Swift, flatMap and compactMap are used for transforming collections but serve different purposes:

  • flatMap is used to transform elements of a collection into collections and then "flatten" (flat) the result into a single level. For example, if each element is transformed into an array, flatMap will combine all these arrays into one.

  • compactMap transforms the elements of a collection while simultaneously discarding all nil (or missing) values. This is useful when the transformation may return an optional value, and you want to get an array with only non-empty results.

Example in Swift:

let numbers = ["1", "2", "three", "4"]

// compactMap converts strings to Int, discarding non-numeric
let ints = numbers.compactMap { Int($0) } // [1, 2, 4]

// flatMap with arrays
let nested = [[1, 2], [3, 4], [5]]
let flat = nested.flatMap { $0 } // [1, 2, 3, 4, 5]

Thus, compactMap filters and transforms, while flatMap combines nested collections after transformation.

Can you explain the difference between flatMap and… - sobes.tech