SWIFT / CHAPTER 07

Transforming and grouping collections

Intermediate

Choose result shapes and preserve ordering intentionally.

By the end of this chapter

  • Choose map, compactMap, or reduce
  • Provide an empty-input accumulator
  • Separate grouping from presentation order

The idea

map transforms every element into a corresponding result. compactMap additionally discards nil transformation results, making it useful for parsing only valid values. reduce combines a sequence into one accumulated result starting from an explicit initial value. The chosen operation should communicate the required result shape rather than simply minimize the number of lines in the implementation.

Grouping and counting add another contract: which keys are present and in what order the results are displayed. A dictionary is useful storage, but sorting its keys explicitly is clearer when an alphabetical report is required. Preserve duplicates when they represent repeated observations. A count or total of zero should not automatically remove a group if the requirement distinguishes observed groups from missing groups.

Swift example
let texts=["4","bad","2"]
let values=texts.compactMap{Int($0)}
print(values)
print(values.reduce(0,+))
Result
[4, 2]
6

The invalid parse yields nil and is discarded; reduction sums the two successful values from a zero starting point.

Try it yourself

Count normalized labels, then present the totals using sorted keys.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does ["0","x","3"].compactMap { Int($0) } produce?