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 wil
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..
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: