1

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?

Top-Master
  • 7,611
  • 5
  • 39
  • 71
  • 2
    Is there a ceiling() function you could call? EDIT - Does this answer do the trick: http://stackoverflow.com/a/24182426/1061011 – Chris Mar 02 '17 at 20:15
  • 1
    I'm confused as to what your goal is... what do you want the last number you loop through to be? – Bryan Mar 02 '17 at 20:17
  • Yeah I'm not really sure what results you're trying to achieve, either. – Alexander Mar 02 '17 at 20:21
  • 1
    See [Swift 3 for loop with increment](http://stackoverflow.com/q/37170203/2976878) – you can use `stride(from:to:by:)`. – Hamish Mar 02 '17 at 20:22
  • Yes, if you're rewriting a .c file in Swift 3, why don't you just set var upperBound = 11 since that's all it seems you need. – Daniel Legler Mar 02 '17 at 20:22
  • @Bawpotter I wan't to loop up to the greatest integer smaller than `upperBound` (e.g. _12_ for `upperBound = 12.3` and _11_ for `upperBound = 12.0`). –  Mar 02 '17 at 20:23
  • @DanielLegler In the real code `upperBound` is dynamic. –  Mar 02 '17 at 20:23
  • From what I understand, it sounds like he wants 12 included in the loop. Looking at this question again, C would loop from [0, 12) like this Swift code with the boundary condition he's testing. All that needs to be done to include 12 would be replacing '<' with '<='. – Chris Mar 02 '17 at 20:24
  • @Chris So `for i in 0.. –  Mar 02 '17 at 20:25
  • Cool. Disregard my most recent comment then, I didn't see your reply to Bawpotter when I was writing it. – Chris Mar 02 '17 at 20:26
  • @Chris You code `ceil(upperBound)` approach does exactly what I want. Thank you. If you write it as an answer I would be more than happy to accept it :) –  Mar 02 '17 at 20:28
  • 1
    @Hamish: Only that `stride(from: 0.0, to: upperBound, by: 1.0)` makes the loop variable a `Double` and you have to convert each value to `Int`. But it is a possible solution of course. – Martin R Mar 02 '17 at 20:39

1 Answers1

0

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.

Community
  • 1
  • 1
Chris
  • 909
  • 8
  • 18