如何使用步骤执行Swift for-in循环?

Ada*_*m S 42 swift

通过在Swift 3.0中删除传统的C风格for循环,我该如何做到以下几点?

for (i = 1; i < max; i+=2) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

在Python中,for-in控制流语句具有可选的步骤值:

for i in range(1, max, 2):
    # Do something
Run Code Online (Sandbox Code Playgroud)

但Swift范围运营商似乎没有相应的:

for i in 1..<max {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*m S 102

"步骤"的Swift同义词是"stride" - 事实上,Strideable协议许多常见的数字类型实现.

相当于(i = 1; i < max; i+=2):

for i in stride(from: 1, to: max, by: 2) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

或者,为了得到相应的i<=max,使用through变体:

for i in stride(from: 1, through: max, by: 2) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

请注意,stride返回StrideTo/ StrideThrough,这符合Sequence,所以任何你可以用序列做,你可以用一个调用的结果做stride(即map,forEach,filter,等).例如:

stride(from: 1, to: max, by: 2).forEach { i in
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

  • 在swift 3中你可以使用全局函数`stride(from:through:by:)`和`stride(from:to:by:)`like`for i in stride(from:1,to:max,by:2) ){...}` (17认同)
  • @MarkoNikolovski请不要将代码添加到其他用户的答案中.我们不想把话放在嘴里.相反,添加一个新的答案.由于此问题已关闭,您可以为链接的副本添加新答案. (3认同)