【发布时间】:2017-07-22 17:57:35
【问题描述】:
我正在为这个 C 风格的 for 循环寻找 Swift 3 Equivalence:
double upperBound = 12.3
for (int i = 0; i < upperBound; ++i) {
// Do stuff
}
我在想这样的事情:
var upperBound = 12.3
for i in 0..<Int(upperBound) {
// Do stuff
}
动态的upperBound 破坏了幼稚的方法。上面的代码不适用于upperBound = 12.3,因为Int(12.3) = 12。 i 将循环通过 [0, ..., 11](12 个除外)。 i in 0...Int(upperBound) 不适用于 upperBound = 12.0,因为 Int(12.0) = 12。 i 将循环通过 [0, ..., 12](包括 12 个)。
Swift 3 处理这种情况的方式是什么?
【问题讨论】:
-
有可以调用的 ceiling() 函数吗?编辑 - 这个答案是否有效:stackoverflow.com/a/24182426/1061011
-
我很困惑你的目标是什么......你希望你循环的最后一个数字是什么?
-
是的,我也不确定你想要达到什么结果。
-
见Swift 3 for loop with increment——你可以使用
stride(from:to:by:)。 -
@Hamish:只有
stride(from: 0.0, to: upperBound, by: 1.0)使循环变量成为Double,您必须将每个值转换为Int。但这当然是一种可能的解决方案。
标签: swift for-loop swift3 range