To reduce an array into a tuple in Swift, we can use the reduce(into:_:)
function. The reduce(into:_:)
function applies a binary operation to each element of the array, with an accumulating value that starts as a default value.
Here's an example:
main.swift238 chars12 lines
This code creates an array of numbers from 1 to 5, then calls reduce(into:_:)
on it. The initial value of the into
parameter is a tuple with two empty arrays of integers. The binary function checks if the current number is even or odd, and appends it to the appropriate array in the tuple.
The result of the reduction is a tuple with two arrays, one containing the even numbers and the other containing the odd numbers.
With Swift's type inference, we don't need to specify the type of the tuple explicitly. The Swift compiler can infer the tuple's type from the initial value and the binary function.
Output:
main.swift31 chars2 lines
gistlibby LogSnag