什么是在Swift循环中向下计数的最佳方式

时间:2014-07-23 19:34:21

标签: swift

for i in 0...10 {
  println("\(i)")
}

...将从0到10计数。从10到0的最佳计数方法是什么?

2 个答案:

答案 0 :(得分:4)

您可以使用reverse来反转范围(或任何集合):

for i in reverse(0...10) {
    println("\(i)")
}

或者,如果您想要更多控制权,可以使用{4}中的stride新内容:

for i in stride(from: 10, through: 0, by: -1) { // includes 0
    println("\(i)")
}

for i in stride(from: 10, to: 0, by: -1) { // doesn't include 0
    println("\(i)")
}

危险区域

如果你感觉很狡猾,你可以定义自己的自定义语法:

/*** NOT RECOMMENDED - confusing code! ***/

operator infix .. { precedence 136 /* 1 higher than ... and ..< */ }

@infix func ..<T: Strideable>(from: T, by: T.Stride) -> (start: T, stride: T.Stride) {
    return (start: from, stride: by)
}
@infix func ..<<T: Strideable>(fromBy: (start: T, stride: T.Stride), to: T) -> StrideTo<T> {
    return stride(from: fromBy.start, to: to, by: fromBy.stride)
}
@infix func ...<T: Strideable>(fromBy: (start: T, stride: T.Stride), through: T) -> StrideThrough<T> {
    return stride(from: fromBy.start, through: through, by: fromBy.stride)
}

Array(0..2..<10) // [0, 2, 4, 6, 8]
Array(0..2...10) // [0, 2, 4, 6, 8, 10]

Array(5..(-1)...0) // [5, 4, 3, 2, 1, 0]
Array(5..(-1)..<0) // [5, 4, 3, 2, 1]

答案 1 :(得分:1)

编辑: Swift 3中不允许使用C风格的for循环。不要这样做。

你可以用传统方式做到:

for var i = 10; i >= 0; i-- {
  println("\(i)")
}

编辑:我使用ReverseRange()删除了代码,因为它已在Beta4中删除