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:

  • http://michael-brown.net/2016/using-stride-to-convert-c-style-for-loops-to-swift-2.2/
  • http://swiftdoc.org/v2.1/protocol/Strideable/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)