为什么我的Swift循环失败,出现错误“Can not form range with end<启动"? [英] Why is my Swift loop failing with error "Can't form range with end < start"?
问题描述
我有一个for循环来检查一个数是否是一个数的因子,然后检查这个因子是否为素数,然后把它加到数组中。根据原来的号码,我会得到一个错误说:
致命错误:无法形成范围结束< / p>开始
几乎每次都发生这种情况,但是对于一些数字来说,它可以正常工作。我找到的唯一数字是9,15和25。
这里是代码:
let num = 16 //或任何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
$ b} // end for
$ b $如果你需要一个动态值范围的循环,我建议使用 stride(to:by:)
而不是 ..<
或 ...
基本上 ..<
或 ...
会在 start_index时崩溃> end_index
。
例如:
让我们在10 ... k {print(i = \(i))}
为i中的10,k = 5
。< k {print(i = \\(i))}
如何解决:
// swift 2.3
$ p $注意:以上的2个块不会打印出任何东西,但其中一个会在执行时崩溃。
let k = 5
for 10.stride(to:k + 1,by:1){print i = \(i))}
for 10.stride(to:k,by:1){print(i = \(i))}
// swift 3.0
let k = 5
for my stride(from:10,through:k,by:1){print(i = \(i))}
为我的步伐(从10到k:1){print(i = \(i))}
参考:
- http://michael-brown.net/2016/using-stride-to-convert-c-style -for-loops-to-swift-2.2 /
- < a href =http://swiftdoc.org/v2.1/protocol/Strideable/ =noreferrer> http://swiftdoc.org/v2.1/protocol/Strideable/
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
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 crashed when execute.
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/
这篇关于为什么我的Swift循环失败,出现错误“Can not form range with end<启动"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!