Say I have an array [1, 2, 3, 4, 5]
. How can I iterate two at a time?
Iteration 1: (1, 2)
Iteration 2: (3, 4)
Iteration 3: (5, nil)
Extension to split the array.
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)]) }
}
}
let result = [1...10].chunked(into: 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With