Iterate over collection two at a time in Swift

前端 未结 7 927
花落未央
花落未央 2020-11-28 16:00

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)
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 16:35

    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)
    

提交回复
热议问题