随着去除传统的C风格的for循环雨燕3.0的,我该怎么办下面?
for (i = 1; i < max; i+=2) { // Do something }
在Python中,for-in控制流语句具有可选的step值:
for i in range(1, max, 2): # Do something
但是Swift范围运算符似乎没有等效项:
for i in 1..<max { // Do something }
“步骤”的Swift同义词是“跨步”(stride)- 实际上是可跨步协议,由许多常见的数值类型实现。
等效于(i = 1; i < max; i+=2):
(i = 1; i < max; i+=2)
for i in stride(from: 1, to: max, by: 2) { // Do something }
或者,要获取等价的i<=max,请使用through变体:
i<=max
through
for i in stride(from: 1, through: max, by: 2) { // Do something }
请注意,stride返回StrideTo/ StrideThrough,这符合Sequence,所以任何你可以用序列做,你可以用一个调用的结果做stride(即map,forEach,filter,等)。例如:
stride
StrideTo
StrideThrough
Sequence
map
forEach
filter
stride(from: 1, to: max, by: 2).forEach { i in // Do something }