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.swift93 chars4 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.swift31 chars2 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.swift81 chars3 lines
Or we can use it to create a new array by filtering out all odd numbers:
main.swift157 chars7 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