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

Constructive Feedback on Checkpoint 4 - 100 Days of SwiftUI

Forums > 100 Days of SwiftUI

As the post entails, I would love some feedback on my code to tackle checkpoint 4. In psuedocode, I figured I would tackle the problem in this way:

create function that takes in a single, INT argument, with throws -> Int (not sure I understand that)

The function does the following:

  1. throws errors if the provided arguement is less than 1 or more than 10000
  2. loops through a range of 10000
    1. if i * i == the argument, we have our answer
    2. if i * i > argument, then we didn't have an int root

Then I did the do/try with error handling. from enumerating my errors to the end of my code was 34 lines. I feel like this was inefficient, so I would love feedback on how this could be improved based on the lessons learned by checkpoint 4.

enum numberError: Error {
    case OutOfBounds, NoRoot
}

func findSqrt(num: Int) throws -> Int {
    var answer: Int = 0
    if num < 1 {
        throw numberError.OutOfBounds
    }
    if num > 10000 {
        throw numberError.OutOfBounds
    }

    for i in 1...10000 {
        if i*i == num {
            answer = i
            break
        } else if i * i > num {
            answer = i - 1
            throw numberError.NoRoot
        }
    }
    return answer
}

var num1 = 8100

do {
    let result = try findSqrt(num: num1)
    print("The square root of \(num1) is \(result)")
} catch numberError.OutOfBounds {
    print("Error: \(num1) is Out of Bounds. Please choose number between 1 and 10,000")
} catch numberError.NoRoot {
    print("No root found for \(num1).")
}

   

A SwiftUI student scratches her grey hair and ponders...

create function that takes an INT argument, with throws -> Int (not sure I understand that)

Kitchen Disaster

If you're cooking biscuits for breakfast, your intent is to serve some biscuits. But if your process screws up, you THROW the burnt mess into the rubbish bin and send an apology note to your guests. The note might be one a half-dozen standard excuses: Runny Batter, Burned To Crisp, Not Enough Baking Powder, Hard as Rock, Unusal Consistency, Dropped on the Floor. You're the cook, you need to inform your guests with a good and proper reason.

Coding Disaster

Likewise, the signature of your function tells the programmer that your intention is to return an Int. But if something goes wrong inside the function, you won't return an Int. Instead you will THROW an error, in the form of an enumeration value specifying the type of error encountered.

Please make a note! Here in Checkpoint 4 you are throwing an enumeration value. But in future applications, you might throw an object that has a much richer set of debugging data in the form of an error struct.

Homework Reading Assignment

See 👉🏻Apple Error Documentation

Bad Coding Practice

In some languages lacking the ability to throw an error, you might instead return a numeric error code. For example, you might return a -10 signifying your input was out of bounds. You might return a -42 meaning there is no valid result. Additionally, you might return a -75 to signify the calculation yields an imaginary number. You see the problem with this scheme? Don't do this in your code.

Keep Coding

   

Thought when I saw this @Obelix would have something to say 🤣. Well done on it just a few pointer.

if num < 1 {
    throw numberError.OutOfBounds
}
if num > 10000 {
    throw numberError.OutOfBounds
}

These both throw the same error you may want to look at Day 5 - How to check multiple conditions

for i in 1...10000

Does this need to loop to 10,000 when you know that square root of 10,000 is 100 and this is your bound limit?

var answer: Int = 0

You do not need this as the i is a Int and you can return i if i*i == num is true therfore need need to break as this will exit the method.

else if i * i > num {
    answer = i - 1
    throw numberError.NoRoot
}

This else is not required as if the for in loop get to the end then it can just throw numberError.NoRoot

I am interested if you able to refactor the code.

PS When using for in loop instead of if you can use for i in 1...100 where some bool, This is not what you have learned upto now but you might want to look it up as extra.

   

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.