reduce array to tuple in swift

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.swift
let array = [1, 2, 3, 4, 5]

let result = array.reduce(into: (even: [Int](), odd: [Int]())) {tuple, number in
    if number % 2 == 0 {
        tuple.even.append(number)
    } else {
        tuple.odd.append(number)
    }
}

print(result)
238 chars
12 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.swift
(even: [2, 4], odd: [1, 3, 5])
31 chars
2 lines

gistlibby LogSnag