guard let in swift 2.0 playground 获取有关可选绑定的错误...为什么?

guard let in swift 2.0 playground gets error about optional binding... why?

我在看this video。在 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 { [=11=] > 0 }
}

当我将其输入 Xcode 游乐场时,出现以下错误:

Initializer for conditional binding must have Optional type, not 'Int.'

这是为什么?

这里的"problem"就是语句guard let prime = numbers[i]。编译器抱怨它,因为 guard let 语法期望 numbers[i] 是一个 Optional,它可以有条件地解包。但这不是可选的,您始终可以从数组中检索 i-th Int

要修复它,只需写

let prime = numbers[i]
guard prime > 0 else { continue }

stride 的正确用法如下所示(在评论中搜索了很长时间之后):

for multiple in (2*prime-2).stride(to: n-2, by: 2*prime-2) {

那么最后一块就是改print:

print("\(numbers[i])")