The Swift Standard Library API specifies that Array has a method reduce(into:_:)
that returns the result of combining the elements of the sequence using the given closure.
The API docs mention that "you can use this method on an array of integers to filter adjacent equal entries". Can someone provide an example of how this would be done?
You could eliminate runs of equal numbers like this:
let numbers = [1, 1, 2, 2, 2, 3, 4, 4, 5, 4, 3]
let filtered = numbers.reduce(into: [Int]()) { newArray, number in
if newArray.last != number { newArray.append(number) }
}
print(filtered)
[1, 2, 3, 4, 5, 4, 3]