说我有一个数组[1, 2, 3, 4, 5]。如何一次迭代两个?
[1, 2, 3, 4, 5]
Iteration 1: (1, 2) Iteration 2: (3, 4) Iteration 3: (5, nil)
您可以使用称为stride(to :, by :)的进度循环,每n个元素对元素进行一次迭代:
Xcode 8.3.2•Swift 3.1
let array = Array(1...5) let pairs = stride(from: 0, to: array.endIndex, by: 2).map { (array[$0], $0 < array.index(before: array.endIndex) ? array[$0.advanced(by: 1)] : nil) } // [(.0 1, {some 2}), (.0 3, {some 4}), (.0 5, nil)] print(pairs) // "[(1, Optional(2)), (3, Optional(4)), (5, nil)]\n"