3 min readFeb 20, 2026
SwiftHow to Use map, filter, reduce
Transform collections with functional helpers.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- Adjust the inputs to match your use case.
Copy and paste
import Foundation
let numbers = [1, 2, 3, 4, 5]
let evens = numbers.filter { $0 % 2 == 0 }
let squares = numbers.map { $0 * $0 }
let total = numbers.reduce(0, +)
print(evens)
print(squares)
print(total)Notes
- Keep functions small and focused for reuse.
- Prefer safe APIs like optionals and guards.
