For loop decrement in Swift 2.2

Hi,


I have been using C style for loop for decrement.


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



It seems like " for i in 10 ... 0 " doesn't work.

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


How can I do this in Swift 2.2 or later?



Thanks in advance.

Jin

Accepted Reply

The nearest equivalent is something like:


for i in 10.stride (through: 0, by: -1) {
  print("\(i)")
}

Replies

The nearest equivalent is something like:


for i in 10.stride (through: 0, by: -1) {
  print("\(i)")
}

I think you can do this too:


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

Oops, I forgot about this one:


(0...10).reverse().forEach{print($0)}

I have tried this with CGFloat and i am getting the following error: Can not invoke stride with an argument list of type '(CGFloat by: CGFloat)'


from:

for var min:CGFloat = 0.0; min<=45.0; min = min+value {

print("\(min)")

}


to:

for min:CGFloat in 0.stride(CGFloat(55.0), by: min+value) {

print("\(min)")

}

'0.stride…' invokes 'stride' on a literal, which (in the absence of other information) the compiler treats as an Int. Int's 'stride' method doesn't take CGFloat parameters, hence the error.


You also have two other errors. The first parameter of 'stride' requires a 'to' or 'through' keyword, and you can't (and don't want to) use the variable 'min' in the stride amount. So the correct syntax would be like this:


for min in CGFloat (0).stride(to: 55, by: value) {
  print("\(min)")
}


Note that once you've specified the correct type for the literal 0, the compiler can infer CGFloat for all of the other numbers in the statement.