6

for example, a Java for-loop:

for(int i=0; i<5; i+=1){
   //
}

convert to Swift

for index in 0..<5 {
}

but what if i+=2?

I'm new to Swift.. Maybe it's a stupid question, but will be appreciate if you answer it, thx! :-)

voicebeer
  • 79
  • 1
  • 4

3 Answers3

37

Check this

for index in stride(from: 0, to: 5, by: 2){
    print(index)
}
Uma Madhavi
  • 4,851
  • 5
  • 38
  • 73
2

You can use this way as well.

var first = 0
var last = 10
var add = 2
for i in sequence(first: first, next: { $0 + add })
.prefix(while: { $0 <= last }) {
    print(i)

} 

Output will be: 0,2,4,6,8,10

Muhammad Shauket
  • 2,643
  • 19
  • 40
1

In case if your for loop was doing something more complex than adding constant value to index each iteration you may use something like that:

Assuming you have this for loop:

for(index = initial; condition(index); mutation(index)){
   //
}

Where

  • initial — initial value constant of type T
  • condition — function (T) -> Bool, that checks if loop should end
  • mutation — function (T) -> T, that changes index value each iteration

Then it will be:

for index in sequence(first: initial, next: { current in
    let next = mutation(current)
    return condition(next) ? next : nil
}) {
   //
}
user28434'mstep
  • 6,290
  • 2
  • 20
  • 35