reduce an array swift in swift

To reduce an array in Swift, we use the reduce method which iterates over the array and combines all elements into a single value based on a given closure. The closure takes in two arguments - the current accumulated value and the next element in the array. Below is an example of reducing an array of numbers to their sum:

main.swift
let numbers = [3, 5, 7, 9]
let sum = numbers.reduce(0, { $0 + $1 })
print(sum) // output: 24
93 chars
4 lines

In the above example, 0 is the initial value for the accumulator, and the closure { $0 + $1 } specifies how to combine the accumulator and each element of the array.

We can also use the shorthand syntax for the closure when the operation is as simple as addition:

main.swift
let sum = numbers.reduce(0, +)
31 chars
2 lines

We can also use reduce to perform other operations on an array. For example, we can use it to find the maximum element in an array:

main.swift
let max = numbers.reduce(Int.min, { Swift.max($0, $1) })
print(max) // output: 9
81 chars
3 lines

Or we can use it to create a new array by filtering out all odd numbers:

main.swift
let evens = numbers.reduce(into: []) { result, number in
    if number % 2 == 0 {
        result.append(number)
    }
}
print(evens) // output: [3, 5, 7, 9]
157 chars
7 lines

In the above example, result is the accumulator and we add elements that match the condition to it. The into keyword specifies that a new array should be created as the initial value for the accumulator.

gistlibby LogSnag