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

SOLVED: Checkpoint 4 - Verbosity

Forums > 100 Days of SwiftUI

Hello to you all,

In checkpoint 4 I managed to solve the solution after much thinking, looking for missing pieces of information in past lectures and even googling (in other languages). I came up with a solution that seems too verbose especially after seeing the solution from Paul Hudson.

Code:

import Cocoa

enum squareError: Error {
    case outOfBounds, noRoot
}
func squareRoot(firstNum: Int) throws -> Int {
    var result = 0

    for i in 1...10_000 {
        let powerOfTwoResult = i * i
        if firstNum < 1 || firstNum > 10_000 {
            throw squareError.outOfBounds

        } else if powerOfTwoResult != i * i {
            throw squareError.noRoot

        } else if powerOfTwoResult == firstNum {
            result = i
            print("The square root of \(firstNum) is \(result)")

        }
    }
    return result
}

do {
    try squareRoot(firstNum: 25)
} catch squareError.outOfBounds {
    print("Out of bounds.")
} catch squareError.noRoot {
    print("Could not find square root.")
}

Something in my brain tells me this is just a bad solution, too much clutter. I used else ifs but paul just used two if statements, I made a variable to hold a value of "0" and then inside the for loop I made another variable that held the expression "i * i" to later then use it, You get the idea I hope that I did "too much" was this wrong? What could I have changed in my code to make it better, without just simply copy pasting Paul's solution? Thank you for taking the time to read this, I look forward to your answers!

   

Great job(ish). You're understanding the mnemonics. That's a great thing! The logic part maybe not so much. In Engineering the best way to approach a subject is take a large problem and break it down into smaller problems. You'll hear that a lot....

Let's look at one of the smaller parts you have written.....

for i in 1...10_000 {
        let powerOfTwoResult = i * i
        if firstNum < 1 || firstNum > 10_000 {
        throw squareError.outOfBounds

If you stand back and really think about what you are actually doing here then you'll probably think oh bloody hell, what was I thinking?.....

If not let's look at what you're actually doing.

You are executing a for loop..... for i in 1...10_000 {

Meaning this part and everything in the loop will loop 10000 times..... if firstNum < 1 || firstNum > 10_000 { throw squareError.outOfBounds

Meaning you are checking that your firstNum is less than 1 or greater than 10000..... That's great and all, but you are checking it/the same thing ten thousand times, where you should only need to check it once before you return the verdict. How to correct that.....I think you'll figure it out now that you have direction.

I would not dwell on this too much though...If at all, because through the course and doing more of logic and code you'll get a lot better and if you actually "return" pardon the the pun! To some of these starter checkpoints later on you will be doing them with your eyes closed.

Lastly make sure you use a catch all errors so that you can give the user a pleasant message. I often think about putting in a mission impossible theme tune when that happens, but that's just me/my preference. A picture of a fluffy white dog with an "Oops no treats for you" message might be good thing as well.

Keep going you'll do great!

1      

Some notes...

  1. Check your bounds condition at the outset so you avoid doing any processing if it fails.
  2. Your if powerOfTwoResult != i * i check will never pass, because right at the beginning of your loop, you explicitly set powerOfTwoResult = i * i
  3. IMO, it's better to check if you have a match and return if you do, then if you make it all the way through the loop without matching anything, you can throw a noRoot error. But that's mostly a personal style thing, I think
  4. Speaking of style, the Swift convention is to start type names with a capital letter, so SquareError instead of squareError. Following this convention will benefit you in the long run.

2      

I see, Thank you both for your answers!

   

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.