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

你。 提交于 2019-11-26 06:44:18

问题


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

回答1:


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



回答2:


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.




回答3:


From swift 3.0, The stride(to:by:) method on Strideable has been replaced with a free function, stride(from:to:by:)

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



回答4:


You can use stride method:

10.stride(through: 0, by: -1).forEach { print($0) }

or classic while loop.




回答5:


If you still want to use this C-style loop, here is what you need:

let x = 10

infix operator ..> { associativity left }
func ..>(left: Int, right: Int) -> StrideTo<Int> {
    return stride(from: left, to: right, by: -1)
}

for i in x..>0 {
    print(i)
}


来源:https://stackoverflow.com/questions/35032182/decrement-index-in-a-loop-after-swift-c-style-loops-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!