Menu
Coddy logo textTech

Chaining map, filter, reduce

Part of the Logic & Flow section of Coddy's Swift journey — lesson 26 of 56.

The real power of these three methods is that they compose. Each step transforms the data and hands it to the next.

let nums = [1, 2, 3, 4, 5, 6]
let result = nums
    .filter { $0 % 2 == 0 }      // [2, 4, 6]
    .map { $0 * $0 }             // [4, 16, 36]
    .reduce(0, +)                // 56
print(result)                    // 56

Reading top to bottom: keep evens, square them, sum the squares. Each step is one obvious thing, the chain stays readable even as it grows.

This pipeline shape replaces a hand-written loop with explicit intent. filter says "select". map says "transform". reduce says "collapse".

A reader can scan the chain and see what's happening without tracing index variables.

One quick rule: order matters. Filtering before mapping does less work than mapping before filtering when the filter is selective.

challenge icon

Challenge

Medium

Read a single line of input: a comma-separated list of price:quantity pairs. For example, 3:2,5:1,2:4,7:0 means four orders.

For every order with quantity > 0, the line total is price * quantity. Print three lines:

  1. The line totals (only for orders with quantity > 0), joined with ,
  2. The grand total of those line totals
  3. The number of orders that contributed (i.e. quantity above zero)

Build the pipeline with filter followed by map, then derive the count and the sum from the result.

For input 3:2,5:1,2:4,7:0, the output is:

6,5,8
19
3

Try it yourself

let orders = readLine()!.components(separatedBy: ",").map { pair -> (Int, Int) in
    let parts = pair.components(separatedBy: ":")
    return (Int(parts[0])!, Int(parts[1])!)
}

// TODO: filter quantity > 0, map to line totals; print joined, sum, count
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow