Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 970
lagoon Avatar asked Feb 22 '15 21:02

lagoon


1 Answers

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/
like image 54
nahung89 Avatar answered Oct 24 '22 16:10

nahung89