UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Checkpoint 4

Forums > 100 Days of SwiftUI

Hello!

Im getting an error: Missing return in a function expected to return 'Int. Where this return Int should be?


enum SquareRootError: Error {
    case outofbounds, noroot
}

func lookForSquareRoot(_ number: Int) throws -> Int {
    if number < 1 || number > 10000 {
        throw SquareRootError.outofbounds
    }
    for i in 1...10000 {  // im not sure tu use 100 or 10000
        if number == i * i {
            return i
        } else {
            throw SquareRootError.noroot
        }
    }
} //Error: Missing return in a function expected to return 'Int

let checkNumber = 6661

do {
    let resoultNumber = try lookForSquareRoot(checkNumber)
    print("The square root of \(checkNumber) is \(resoultNumber)")
}
    catch {
        print("There was an error.")
    }

2      

Your For Loop logic is wrong, as you are checking to throw an error for each iteration of the loop.

for i in 1...10000 {  // im not sure tu use 100 or 10000
    if number == i * i {
        return i
    } else {
        throw SquareRootError.noroot
    }
}

Only throw the no root error once the For Loop is exhausted. Also use 100 not 10000, as the check is i times i , therefore the maximum is 100 * 100 (= 10000)

for i in 1...100 {  // use 100, because i * i
    if number == i * i {
        return i
    }
}
throw SquareRootError.noroot

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.