tezvyn:

map versus compactMap versus flatMap

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

functional transforms on sequences.

OUTLINE

map transforms each element one-to-one; compactMap transforms then drops nils; flatMap transforms to sequences then concatenates.

WHAT THIS TESTS It checks fluency with the standard library's transform functions and awareness of the historical flatMap-versus-compactMap rename that still trips people up.

MAP map applies a transform to each element and returns an array of the same length, one output per input. The element type can change; the count cannot. Example: [1, 2, 3].map { $0 * 2 } yields [2, 4, 6].

COMPACTMAP compactMap applies a transform that returns an Optional, then discards every nil and unwraps the rest, so the result can be shorter. It is the idiomatic way to transform-and-filter in one pass. Example: ["1", "x", "3"].compactMap { Int($0) } yields [1, 3] because "x" maps to nil and is dropped.

FLATMAP flatMap on a sequence applies a transform that itself returns a sequence and concatenates those sequences into a single flat array, reducing one level of nesting. Example: [[1, 2], [3, 4]].flatMap { $0 } yields [1, 2, 3, 4]. Historically flatMap also had an overload that filtered Optionals; that role moved to compactMap to remove ambiguity.

COMMON WRONG ANSWERS Saying flatMap removes nils, which describes the deprecated overload now served by compactMap. Claiming map can change the element count. Thinking compactMap flattens nested arrays.

LIKELY FOLLOW-UPS Why was the nil-filtering flatMap deprecated? What does flatMap do on an Optional versus a sequence? How would you flatten and filter nils in one chain? What is the complexity of these operations?

ONE CONCRETE EXAMPLE Parsing user input lists of comma-separated numbers across several lines, you write lines.flatMap { 0.split(separator: ",") }.compactMap { Int(0) }. flatMap concatenates the per-line tokens into one sequence, then compactMap converts each to an Int and silently drops anything that is not a valid number, giving a single clean array of integers.

Read the original → donnywals.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.