Skip to content
Higher-Order Methods
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

All standard Swift collections support a rich set of higher-order methods:

let nums = [1, 2, 3, 4, 5]

nums.map { $0 * $0 }              // [1, 4, 9, 16, 25]
nums.filter { $0 > 2 }             // [3, 4, 5]
nums.reduce(0, +)                  // 15
nums.reduce(0) { acc, n in acc + n }   // explicit form

nums.first(where: { $0 > 3 })      // Optional(4)
nums.contains(where: { $0 > 4 })   // true
nums.allSatisfy { $0 > 0 }         // true
nums.sorted(by: >)                  // [5, 4, 3, 2, 1]

compactMap is map + filter-out-nil — useful for transforming + parsing in one step:

let strings = ["1", "2", "abc", "4"]
let ints = strings.compactMap { Int($0) }   // [1, 2, 4]

flatMap flattens nested sequences. Combined with these tools, you can build dense, expressive transforms.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…