Search code examples
swiftfor-loopswift3range

Swift 3 - round-up double of for-loop


I'm looking for an Swift 3 Equivalence for this C-style for-loop:

double upperBound = 12.3
for (int i = 0; i < upperBound; ++i) {
  // Do stuff
}

I was thinking about something like this:

var upperBound = 12.3
for i in 0..<Int(upperBound) {
  // Do stuff
}

A dynamic upperBound ruins the naive approach. The code above won't work for upperBound = 12.3, since Int(12.3) = 12. i would loop through [0, ..., 11] (12 excluded). i in 0...Int(upperBound) won't work for upperBound = 12.0, since Int(12.0) = 12. i would loop through [0, ..., 12] (12 included).

What is the Swift 3 way of handling situations like this?


Solution

  • Credit to Martin R for this more Swift-y answer:

    You can make use of the FloatingPoint protocol, whose behavior is detailed here, to always round up: upperBound.rounded(.up)

    Original Answer:

    Based on this answer, using ceil(upperBound) will cause any value greater than (in your example) 12 to be rounded up to 13.