-1

I'm getting the error "missing return in function expected to return 'Bool'" but I can't figure out why.

func isPrime(_ number: Int) -> Bool {
   for primeDivisors in 2..<number {
       if number % primeDivisors == 0 {
           return true
       } else {
           return false
       }
   }
}

isPrime(13)
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Tom
  • 81
  • 10
  • If you call `isPrime(1)` your `for` loop will never execute and the function will never hit a `return` statement. – vacawama Jun 16 '17 at 02:39

2 Answers2

1

Your prime checker is incorrect, because the very first iteration of the loop returns a value. You have to go through the entire loop before deciding that the number is prime.

func isPrime(_ number: Int) -> Bool {
    for primeDivisors in 2..<number {
        if number % primeDivisors == 0 {
            return false
        }
    }
    return true
}

Note that this code is inefficient, because it continues checking divisibility more times than it is necessary: you can stop checking upon reaching square root of number.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

It's complaining because not all code paths end up returning something. What happens if number is less than 2? Then your for loop, and the return statements inside it, will never be called, and there's no return that happens after the for loop finishes.

NRitH
  • 13,441
  • 4
  • 41
  • 44