WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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 Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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.