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 Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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.