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

前端 未结 5 1595
谎友^
谎友^ 2020-11-27 20:09

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{
           


        
5条回答
  •  庸人自扰
    2020-11-27 20:31

    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.

提交回复
热议问题