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

拜拜、爱过 提交于 2019-12-20 17:36:43

问题


I have a for loop that checks if a number is a factor of a number, then checks if that factor is prime, and then it adds it to an array. Depending on the original number, I will get an error saying

fatal error: Can't form range with end < start

This happens almost every time, but for some numbers it works fine. The only numbers I have found to work with it are 9, 15, and 25.

Here is the code:

let num = 16 // or any Int
var primes = [Int]()

for i in 2...(num/2) {

    if ((num % i) == 0) {
        var isPrimeFactor = true

        for l in 2...i-1 {
            if ((i%l) == 0) {
                isPrimeFactor = false;
            }//end if
        }//end for

        if (isPrimeFactor == true) {
            primes.append(i)
        }//end if

    }//end if

}//end for

回答1:


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:

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



回答2:


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




回答3:


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:)



来源:https://stackoverflow.com/questions/28663749/why-is-my-swift-loop-failing-with-error-cant-form-range-with-end-start

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