NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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.")
    }

   

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

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.