Ashley Rodrigues Ashley Rodrigues - 5 months ago 34
iOS Question

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

Answer

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