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

依然范特西╮ 提交于 2019-12-03 04:25:56
nahung89

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.

Ex:

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

How to fix:

// swift 2.3
let k = 5
for i in 10.stride(to: k+1, by: 1) { print("i=\(i)") }
for i in 10.stride(to: k, by: 1) { print("i=\(i)") }

// swift 3.0
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: 2 blocks above won't print out anything, but one of them will be crash upon execution. 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:

In your second loop, i will always start at 2, which means you're looping from 2...1

SWIIFT 4

The best way to go is to use stride as by this documentation page: Generic Function stride(from:to:by:)

for i in stride(from: 10, through: 5, by: -1) { print(i) }

and stride through if you want to include the lowerBound: Generic Function stride(from:through:by:)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!