Guard in swift 2.0, the site receives an error about optional binding ... why?

I watched this video . At 9:40 or so, there is an example code on the screen that looks like this:

//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 enter it into the Xcode playground, I get the following error:

The conditional binding initializer must be of an optional type, not 'Int.'

Why is this?

+5
source share
1 answer

The โ€œproblemโ€ here is the statement guard let prime = numbers[i] . The compiler complains about this because the guard let syntax expects numbers[i] be optional, which it can conditionally expand. But this is not necessary, you can always extract the i-th Int from an array.

To fix it, just write

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

The proper use of stride then looks like this (after a long search in the comments):

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

Then the final part should change print :

 print("\(numbers[i])") 
+2
source

Source: https://habr.com/ru/post/1239488/


All Articles