GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Checkpoint 4 Question

Forums > 100 Days of SwiftUI

Question on my function for Checkpoint 4 of finding the sqrt for a number between 1 and 10,000.

I was getting an error that my func expected to return 'Int'. As a workaround, I created another error case "unknown" and added "throw sqrtError.unknown". I assume this is probably a poor solution, but I was struggling to figure out an alternative. Feedback welcome.

enum sqrtError: Error {
    case outOfBounds, noRoot, unknown
}

func findSqRt(number: Int) throws -> Int {
    if number >= 1 && number <= 10000 {
        for i in 0...number {
            if i < number {
                if i*i == number {
                    return i
                }
            } else {
                throw sqrtError.noRoot
            }
        }
    } else {
        throw sqrtError.outOfBounds
    }
    throw sqrtError.unknown
}

do {
    let answer = try findSqRt(number: 10000)
    print("Square root = \(answer)")
} catch sqrtError.outOfBounds {
    print("Number is out of bounds")
} catch sqrtError.noRoot {
    print("Square root cannot be found")
} catch sqrtError.unknown {
    print("Unknown error")
}

   

@MattX  

  1. Your code has a lot of unnecessary nesting. You can make your code a bit cleaner using a guard statement to ensure the number is in the specified range at the beginning and remove one level of indentation.

    guard number >= 1 && number <= 10000 else {
        throw sqrtError.outOfBounds
    }

    Or you could use a bit of a shortcut and check if the range itself contains the number.

    guard (1...10000).contains(number) else {
        throw sqrtError.outOfBounds
    }
  2. You are iterating between 0 and 10,000. Why? The square root of the largest number (10,000) is 100, so you can better optimize your code by only iterating between 1 and 100, because you know that the root, if it exists, will fall in that range of values. (You also do not need to check if i < number in this case.)

    for i in 1...100 {
        if i * i == number {
            return i
        }
    }
  3. Think about where your noRoot error needs to be thrown... After looping through all of the possibe square roots, right? Only then can you ensure that a square root could not be found, since nothing would have been returned. So throw sqrtError.noRoot should be called after the for loop, near the bottom of the function.


Final updated function:

func findSqRt(number: Int) throws -> Int {
    guard number >= 1 && number <= 10000 else {
        throw sqrtError.outOfBounds
    }

    for i in 1...100 {
        if i * i == number {
            return i
        }
    }

    throw sqrtError.noRoot
}

1      

While I would probaly use guard as it shows the "happy" path better, at this stage you have not been shown this. The reason for the error is that need to return an Int or Error. By moving thethrow sqrtError.outOfBounds out of the if statement you will get the same result.

func findSqRt(number: Int) throws -> Int {
    if number >= 1 && number <= 10000 {
        for i in 0...100 {
            if i < number {
                if i*i == number {
                    return i
                }
            }
        }

        throw sqrtError.noRoot
    }

    throw sqrtError.outOfBounds
}

Also you do not need to for loop to do to 10000 as this is 100 and therfore do not need the check to see if it less then number, if get to the end of loop then there is noRoot

Well done. As a new challenge try to use the Swift’s built-in sqrt() function. This will take use a Double but you need only to find Int number!

1      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.