Decrement index in a loop after Swift C-style loops deprecated

netshark1000 picture netshark1000 · Jan 27, 2016 · Viewed 22.2k times · Source

How would you express a decrementing indexed loop in Swift 3.0, where the syntax below is not valid any more?

for var index = 10 ; index > 0; index-=1{
   print(index)
}

// 10 9 8 7 6 5 4 3 2 1

Answer

Jonny picture Jonny · Sep 29, 2016

Here is an easier (and more Swifty) approach.

for i in (0 ..< 5).reversed() {
    print(i) // 4,3,2,1,0
}

let array = ["a", "b", "c", "d", "e"]
for element in array.reversed() {
    print(element) // e,d,c,b,a
}

array.reversed().forEach { print($0) } // e,d,c,b,a

print(Array(array.reversed())) // e,d,c,b,a