Search code examples
iosswiftfor-in-loopxcode7.3

How to use for in loop decrement condition in swift?


I can use the for in loop in Swift through this code

   for i in 0..<5
{
    print ("Four multiplied by \(i) results in \(i*4)" )
}

But how do i use the for with less than ">" condition.

  for i in 10>..5
{
    print ("Four multiplied by \(i) results in \(i*4)" )
}

It shows error: '>' is not a postfix unary operator for i in 10>..5


Solution

  • Use the stride() method:

    for i in 10.stride(to: 5, by: -1) {
         print ("Four multiplied by \(i) results in \(i*4)" )
    }
    

    This will increment through 10, 9, 8, 7, and 6. If you want 5 to be included, use through: instead:

    for i in 10.stride(through: 5, by: -1) {
         print ("Four multiplied by \(i) results in \(i*4)" )
    }