Swift map, filter, reduce

Swift map, filter, reduce

Transform and aggregate collections with mapfilter, and reduce.


Transform and aggregate with map/filter/reduce

Use map to transform elements, filter to select a subset, and reduce to combine into a single result.

Example

let nums = [1, 2, 3, 4]
let doubled = nums.map { $0 * 2 }
print(doubled)
let evens = nums.filter { $0 % 2 == 0 }
print(evens)
let sum = nums.reduce(0, +)
print(sum)


Convert and Sum

Use compactMap to convert valid strings to numbers, then reduce to sum.

Example

let raw = ["1", "x", "2", "3"]
let ints = raw.compactMap { Int($0) }   // [1, 2, 3]
let total = ints.reduce(0, +)
print(total)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *