I was watching this video. At 9:40 or so there is some sample code on the screen that looks like the code below:
我在看这个视频。在9:40左右,屏幕上有一些示例代码,如下面的代码:
//Sieve of Eratosthenes, as seen in WWDC 2015
func primes(n: Int) -> [Int] {
var numbers = [Int](2..<n)
for i in 0..<n-2 {
guard let prime = numbers[i] where prime > 0 else { continue }
for multiple in stride(from: 2 * prime-2, to: n-2, by: prime) {
numbers[multiple] = 0
print("\"numbers[i]")
}
}
return numbers.filter { $0 > 0 }
}
When I type that into an Xcode playground, I get the following error:
当我在Xcode游乐场中键入它时,我收到以下错误:
Initializer for conditional binding must have Optional type, not 'Int.'
条件绑定的初始化程序必须具有Optional类型,而不是'Int。'
Why is that?
这是为什么?
1 个解决方案
#1
2
The "problem" here is the statement guard let prime = numbers[i]
. The compiler complains about it because the guard let
syntax expects numbers[i]
to be an Optional which it can conditionally unwrap. But it is not an optional, you are always able to retrieve the i-th Int
out of the array.
这里的“问题”是声明保护让prime = numbers [i]。编译器抱怨它,因为guard let语法要求numbers [i]是一个可选的,它可以有条件地解包。但它不是可选的,你总是可以从数组中检索第i个Int。
To fix it simply write
修复它只需写
let prime = numbers[i]
guard prime > 0 else { continue }
The correct usage of the stride
then looks like the following (after a long search in the comments):
然后正确使用步幅如下(在评论中长时间搜索之后):
for multiple in (2*prime-2).stride(to: n-2, by: 2*prime-2) {
Then final piece is then to change the print
:
然后最后一块是改变印刷品:
print("\(numbers[i])")
#1
2
The "problem" here is the statement guard let prime = numbers[i]
. The compiler complains about it because the guard let
syntax expects numbers[i]
to be an Optional which it can conditionally unwrap. But it is not an optional, you are always able to retrieve the i-th Int
out of the array.
这里的“问题”是声明保护让prime = numbers [i]。编译器抱怨它,因为guard let语法要求numbers [i]是一个可选的,它可以有条件地解包。但它不是可选的,你总是可以从数组中检索第i个Int。
To fix it simply write
修复它只需写
let prime = numbers[i]
guard prime > 0 else { continue }
The correct usage of the stride
then looks like the following (after a long search in the comments):
然后正确使用步幅如下(在评论中长时间搜索之后):
for multiple in (2*prime-2).stride(to: n-2, by: 2*prime-2) {
Then final piece is then to change the print
:
然后最后一块是改变印刷品:
print("\(numbers[i])")