Swift 中“step”的同义词是“stride”——可跨步协议 https://developer.apple.com/documentation/swift/strideable事实上,由许多常见的数字类型 http://swiftdoc.org/v2.1/protocol/Strideable/hierarchy/.
相当于(i = 1; i < max; i+=2)
is:
for i in stride(from: 1, to: max, by: 2) {
// Do something
}
或者,为了得到等价的i<=max
, 使用through
变体:
for i in stride(from: 1, through: max, by: 2) {
// Do something
}
注意stride
返回一个StrideTo https://developer.apple.com/documentation/swift/strideto/StrideThrough https://developer.apple.com/documentation/swift/stridethrough,符合Sequence https://developer.apple.com/documentation/swift/sequence,因此您可以对序列执行的任何操作,都可以对调用的结果执行stride
(ie map
, forEach
, filter
, ETC)。例如:
stride(from: 1, to: max, by: 2).forEach { i in
// Do something
}