map, filter and reduce
Collections support functional operations: map transforms, filter keeps matches, reduce combines, sorted orders and compactMap drops nil. Closures use $0 for the first argument.
Example
let n = [1, 2, 3, 4, 5, 6]
print(n.map { $0 * 2 })
print(n.filter { $0 % 2 == 0 })
print(n.reduce(0, +))
print(["3", "x", "5"].compactMap { Int($0) })Exercise
Transform every item.
n. { $0 * 2 }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.