Building Pipelines
Part of the Logic & Flow section of Coddy's Swift journey — lesson 31 of 56.
The methods you've collected, map, filter, reduce, compactMap, flatMap, sorted(by:), are the everyday Swift toolkit. Real code stitches them together.
struct Order {
let item: String
let qty: Int
}
let orders = [Order(item: "apple", qty: 3), Order(item: "bread", qty: 0), Order(item: "milk", qty: 5)]
let names = orders
.filter { $0.qty > 0 }
.sorted { $0.qty > $1.qty }
.map { $0.item }
print(names) // ["milk", "apple"]Read the chain top to bottom: keep non-empty orders, sort by quantity descending, then keep only the names.
Pipelines win when each step has one purpose. If you find yourself doing two things at once inside a closure (mapping and filtering), split them into two steps. The chain stays readable as it grows.
Challenge
MediumRead a single line of input: a comma-separated list of name:price:qty entries. Some entries are malformed and should be skipped: any entry whose price or quantity is not a valid integer.
Build a pipeline that produces one line per valid entry with qty > 0, sorted by total (price * qty) descending, in the format:
<name>: <total>After the per-item lines, print one summary line: Sum: <n> with the grand total.
For input apple:3:2,bread:bad:1,milk:4:5,cheese:8:0,salt:2:7, the output is:
milk: 20
salt: 14
apple: 6
Sum: 40Cheat sheet
Chaining higher-order functions creates readable pipelines where each step has one purpose:
let names = orders
.filter { $0.qty > 0 }
.sorted { $0.qty > $1.qty }
.map { $0.item }
Common pipeline methods: filter → compactMap → sorted(by:) → map → reduce. If a closure does two things at once (e.g. mapping and filtering), split it into two steps.
Try it yourself
let entries = readLine()!.components(separatedBy: ",")
// TODO: pipeline using compactMap (parse), filter (qty > 0),
// sorted (total desc), map (format); print lines + Sum
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check