【问题标题】:Swift 3 - Alternative for C-style for loop (loop while int smaller double)Swift 3 - C 风格 for 循环的替代方案(循环 while int small double)
【发布时间】: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) = 12i 将循环通过 [0, ..., 11]12 个除外)。 i in 0...Int(upperBound) 不适用于 upperBound = 12.0,因为 Int(12.0) = 12i 将循环通过 [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


【解决方案1】:

感谢 Martin R 提供了这个更 Swift-y 的答案:

您可以使用行为为 detailed here 的 FloatingPoint 协议来始终向上取整: upperBound.rounded(.up)

原答案:

基于this answer,使用ceil(upperBound) 将导致任何大于(在您的示例中)12 的值向上舍入到13。

【讨论】:

  • upperBound.rounded(.up)
  • 我更喜欢这个,你是想做出新的答案还是我应该编辑我的?
  • 不需要单独的答案,请随意编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 2019-02-15
  • 1970-01-01
  • 2017-08-06
  • 2015-07-30
  • 1970-01-01
相关资源
最近更新 更多