-1

I have a Swift for loop defined like this:

 for i in 20...1 {
    array.append(i)
 }

But I get a crash with message

  Thread 1: Fatal error: Can't form Range with upperBound < lowerBound

What is the fix?

Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131

2 Answers2

11

You need to reverse the range:

for i in (1...20).reversed() {
    array.append(i)
}
Gereon
  • 17,258
  • 4
  • 42
  • 73
3

You cannot loop in reverse order like that, if you want you can try this :

for i in stride(from: 20, through: 1, by: -1) {
    array.append(i)
}
JeremyP
  • 84,577
  • 15
  • 123
  • 161
Tung Vu Duc
  • 1,552
  • 1
  • 13
  • 22