在 Swift 弃用 C 样式循环后循环递减索引

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

您如何在 Swift 3.0 中表达递减索引循环,其中下面的语法不再有效?

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

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

C-style可以替换固定递增或递减的循环 通过 stride():

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

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

使用 stride(to: ...)stride(through: ...) 取决于是否 是否应包含最后一个元素。

这是针对 Swift 2. Swift 3 的语法(再次)更改,请参阅 .

您可以使用stride方法:

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

或经典的 while 循环。

swift 3.0 开始,Strideable 上的 stride(to:by:) 方法已替换为自由函数,stride(from:to:by:)

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

// You can also use stride condition like
// {Some Value}.stride(to: 0, by: -1)
// for index in 10.stride(to: 0, by: -1) { }

如果您仍想使用这个 C 风格的循环,这里是您需要的:

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)
}

这是一种更简单(也更快捷)的方法。

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([=10=]) } // e,d,c,b,a

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