Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 239
netshark1000 Avatar asked Jan 27 '16 08:01

netshark1000


2 Answers

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
like image 124
Jonny Avatar answered Nov 06 '22 08:11

Jonny


C-style loops with a fixed increment or decrement can be replaced by stride():

for index in 10.stride(to: 0, by: -1) {
    print(index)
}

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

Use stride(to: ...) or stride(through: ...) depending on whether the last element should be included or not.

This is for Swift 2. The syntax changed (again) for Swift 3, see this answer.

like image 49
Martin R Avatar answered Nov 06 '22 08:11

Martin R