0

I am self-learning to program and I came across this piece of Swift 2.0 code.

someFunction {
    for var i = N; i >= 1; i -= 1 {
        //...
    }
}

This is a "C-Style" code apparently. What exactly is happening in this control flow? Are we starting from N, and subtracting 1 until we get to equal/greater than 1?

Or does the i >= 1 mean that the iteration count must ALWAYS be greater than or equal to one?

  • someFunction do { var i: var = N i >= 1 i -= 1 do { //... } } – Saranjith Apr 06 '17 at 09:11
  • 1
    OP: I realize I might've closed this one a bit too fast, but nonetheless (as this is now deprecated loop syntax): your example above above doesn't relate to Swift, in particular any "C-style" `for` loop. The statement `i >= 1` is the [loop invariant](https://en.wikipedia.org/wiki/Loop_invariant), which is true for each iteration through (the body of) the `for` loop. The statement `x -= 1` is the afterthought of the `for` loop, which is performed immediately after existing the body of the `for` loop for each iteration. In terms of Swift (3), your for loop, given that `N > 0`, is equivalent to: – dfrib Apr 06 '17 at 18:03
  • 1
    `for i in stride(from: N, through: 1, by: -1) { /* ... */ }`. For the `stride` approach, however, `i` is immutable, and in case `N < 1`, the body of this loop will never be entered, whereas for the C-style example, `N < 1` would result in a non-terminating ("infinite") loop. – dfrib Apr 06 '17 at 18:05
  • Thank you, dfri, for taking the time to answer – BossGiveMeArrays Apr 09 '17 at 09:43

0 Answers0