Why is my Swift loop failing with error “Can’t form range with end < start"?

Swift 5

If you need a loop with dynamic value-range, I suggest that using stride(to:by:) instead of ..< or ...

Basically ..< or ... will be crashed if start_index > end_index.

This will be crash:

let k = 5
for i in 10...k { print("i=\(i)") }
for i in 10..<k { print("i=\(i)") }

How to fix:

let k = 5
for i in stride(from: 10, through: k, by: 1) { print("i=\(i)") }
for i in stride(from: 10, to: k, by: 1) { print("i=\(i)") }

NOTE:

The code above won’t print out anything, but it won’t be crash when execution.

Also, if you want to stride from a higher number to a lower number then the by parameter needs to be changed to a negative number.

Reference:

Leave a Comment