在Swift 2.2中替换C风格的循环 [英] Replacement for C-style loop in Swift 2.2
本文介绍了在Swift 2.2中替换C风格的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Swift 2.2弃用了C风格的循环。但是在某些情况下,新范围运算符的工作方式不同。
Swift 2.2 deprecated the C-style loop. However in some cases, the new range operator just doesn't work the same.
for var i = 0; i < -1; ++i { ... }
和
for i in 0..<-1 { ... }
后者将在运行时失败。如果,我可以使用包装循环,但它有点混乱。有时候这种循环很有用。
The later one will fail at run-time. I can wrap the loop with an if
, but it's a bit cluttered. Sometimes this kind of loop is useful.
有什么想法吗?
用例
- 你需要枚举一个数组的所有元素,除了最后一个元素。
- 你需要枚举小数范围内的所有整数,但范围可以是[0.5,0.9],因此没有整数(在一些数学之后),这会产生一个空循环。
推荐答案
虽然它不是漂亮,但你可以使用 stride
:
Although it's not as "pretty", you can use stride
:
for var i in 0.stride(to: -1, by: -1) {
print(i)
}
这篇关于在Swift 2.2中替换C风格的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文