Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over collection two at a time in Swift

Tags:

swift

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)
like image 490
fumoboy007 Avatar asked Dec 31 '15 19:12

fumoboy007


1 Answers

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)
like image 51
Manikandan Avatar answered Oct 13 '22 23:10

Manikandan