for i in 0...10 {
println("\(i)")
}
...will count from 0 to 10. What's the best way to count from 10 to 0?
for i in 0...10 {
println("\(i)")
}
...will count from 0 to 10. What's the best way to count from 10 to 0?
You can use reverse
to reverse a range (or any collection):
for i in reverse(0...10) {
println("\(i)")
}
Or if you want more control, you can use stride
, new in beta 4:
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)")
}
if you're feeling crafty, you can define your own custom syntax:
/*** 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]
EDIT: C-style for loops will not be allowed in Swift 3 don't do it this way.
You can do it the traditional way:
for var i = 10; i >= 0; i-- {
println("\(i)")
}
EDIT: I removed code using ReverseRange() because it was removed in Beta4