0

I facing problem in executing for loop in Swift 3. I can use loop for range operator ... and ..< but in may case, I want something like ..> but its not available.

How do I execute following loop in Swift 3?

var myMax = 20
for var i = myMax ; i >= 0 ; i -= 1 {
   ...
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
PlusInfosys
  • 3,416
  • 1
  • 19
  • 33

3 Answers3

1

It's easy to reverse the loop. User reversed function.

Swift 3

let myMax = 20
for i in (1..<myMax).reversed() {
    print(i)
}

You can also use stride as @ZaidPathan said :

This question have all answers with all versions : How to iterate for loop in reverse order in swift?

Community
  • 1
  • 1
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
1
for i in (1..<20).reversed() {
    print(i)
}

Hope it helps.Read More

Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45
0

Swift 3, You can use stride

var myMax = 20
for var i = myMax ; i > 0 ; i -= 1 {

}

//Equivalent

let myMax = 20
for value in stride(from: 20, to: 0, by: -1){
    print(value)
}


var myMax = 20
for var i = myMax ; i >= 0 ; i -= 1 {

}

//Equivalent

for value in stride(from: 20, through: 0, by: -1){
    print(value)
}
Mohammad Zaid Pathan
  • 16,304
  • 7
  • 99
  • 130