1

How will I be able to implement a C-style for loop like this in Swift 2.2?

for var level: Double = 10; level <= 100; level += 10 {

}
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168

2 Answers2

5
for level: Double in 10.stride(through: 100, by: 10) {
}

or in functional style:

(1...10).map { Double($0) * 10.0 }.forEach {
    print($0)
}

Please, don't use var for iterators and don't change the value of an iterator from inside the loop.

I give more examples in this answer

Community
  • 1
  • 1
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Quite straightforward! – Oleg Gordiichuk Mar 24 '16 at 09:01
  • Thanks. I think old version is more readable, not sure if familiarity bias or not. Functional style isn't readable at all. – Esqarrouth Mar 24 '16 at 09:04
  • 1
    @Esq In this case, I wouldn't use the functional style but it's definitely the familiarity. For functional style it really helps to give a name (e.g. `let printIndex = {... }` and then `.forEach(printIndex)`) to every closure. – Sulthan Mar 24 '16 at 09:06
2

For your specific example, what Sulthan said.

More generally, for truly complex ones, any C-style for loop:

for init; cond; step { statement }

can be converted to while:

init
while (cond) {
  statement
  step
}
Amadan
  • 191,408
  • 23
  • 240
  • 301