BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Checkpoint 4 help

Forums > 100 Days of SwiftUI

Hello guys I know there have been countless posts on checkpoint 4. But I still don't get it and kinda feel like a monkey right now. I've been spending 2+ hours over the last few days. Tried writing it in pseudo code. Then tried reading someone elses pseudo code.

Looked at some people's code example that solved it on the forum but I still wanted to write all of it myself so I decided to not blindly copy paste whatever I found.

So I landed on 2 methods that appartently should work but I still didn't manage to do it.

Method 1

I get an error "missing return in global function expected to return 'Int' " which is weird considering I have a return and I read on this forum that the code should work.

import Cocoa

enum squareRootErrors : Error {
    case outBound, noRoot
}

func squareRoot(_ number: Int) throws -> Int {
    if number < 1 || number > 10_000 {
        throw squareRootErrors.outBound
    }

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

let sqrtInput = 9

do {
  let result = try squareRoot(sqrtInput)
    print("the square root of \(sqrtInput) is \(result)")
} catch squareRootErrors.outBound {
    print("Sorry you are out of bound")
} catch squareRootErrors.noRoot {
    print("No square root found for \(sqrtInput)")
} catch {
    print("Unknown Error")
}

Method 2

I add a var that I can populate with the computation's result. Then return that variable so xcode can stop asking me for a return.

And it works!! Except... It does not. I have no error and xcode prints my results but the fuction keeps running for ever and always gives me the "no square root" error all the time (except if I input 1)

import Cocoa

enum squareRootErrors : Error {
    case outBound, noRoot
}

var sqrtCompute = 0

func squareRoot(_ number: Int) throws -> Int {
    if number < 1 || number > 10_000 {
        throw squareRootErrors.outBound
    }

    for i in 1...100 {
        if number == i * i {
          sqrtCompute = i
        }
        throw squareRootErrors.noRoot
    }
return sqrtCompute
}

let sqrtInput = 9

do {
  try squareRoot(sqrtInput)
    print("the square root of \(sqrtInput) is \(sqrtCompute)")
} catch squareRootErrors.outBound {
    print("Sorry you are out of bound")
} catch squareRootErrors.noRoot {
    print("No square root found for \(sqrtInput)")
} catch {
    print("Unknown Error")
}

So I'm super lost now and I have no idea how to solve this or what even went wrong. It's so cryptic sometimes.

2      

@wonder is learning debugging techniques!

Tried writing it in pseudo code. Then tried reading someone elses pseudo code.

Nice! You've stubbed your toe and now you're asking for help with debugging. Excellent progress. Here's another technique!

Be the Compiler!

In your code below, be the compiler!

What happens if your number is 25 and i is 1 ?

for i in 1...100 {                 // 1. Create a range
    if number == i * i {           // 2. Test for perfect square
        return i                   // 3. Return root, if test proved true
    }                              // 4. End the perfect square test
    throw squareRootErrors.noRoot  // 5. WHAT HAPPENS HERE?
}                                  // 6. End of for-loop

Compiler thinks

Step 1. Roger, 100 values ready to go. First value for i is 1.
Step 2. I see that 1 * 1 == 25 is not true!
Step 3. Disgregard the return statement, the test was FALSE.
Step 4. Formal recognition of the end of the IF condition.
Step 5. Throw the error, then end this code chunk.
Step 6. Formal recognition of the end of the FOR-IN loop.

Compiler: Wait a minute! What if the condition FAILS for every single value from Step 1? If this happens, I'll never return an integer! I better flag this code and alert the programmer!

Keep Coding!

We're here to help.

4      

Probably talking to myself but. I think I have found a solution to at least the Second method.

The issue was that my throw was inside the for loop apparently. Whith that solved the code works. There is still 90% of it that I don't understand but at least this code works 🤣

import Cocoa

enum squareRootErrors : Error {
    case outBound, noRoot
}

func squareRoot(_ number: Int) throws -> Int {
    if number < 1 || number > 10_000 {
        throw squareRootErrors.outBound
    }

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

let input = 16

do {
  let result = try squareRoot(input)
    print("Square root for \(input) is \(result)")
} catch squareRootErrors.outBound {
    print("Sorry you are out of bound")
} catch squareRootErrors.noRoot {
    print("No square root found")
} catch {
    print("Unknown Error")
}

2      

Thanks a lot Obelix! I was talking about your pseu code by the way. It helped me greatly 😁.

And thanks again for this other method. It's pretty cool!

May Jules Cesar never invade your village 😉

2      

@wonder found the solution!

The issue was that my throw was inside the for loop apparently. With that solved the code works.

Yes! Exactly!

You never actually got to #2 in the range. As soon as your code failed testing the value of 1 you instructed the compiler to end the loop by throwing an error.

You made the right correction.

Loop through EVERY value in the range. If none of those value were a perfect square THEN you should toss the error.

Nice find!

3      

Thank you @Obelix and thank you @wonderpig for asking

Be the Compiler!

so simple yet I wasn't being the compiler in my own head and I was really struggling to understand just the square root code, until I became the compiler....

Now I'm off to take a look at the rest of checkpoint 4 solution. as I too am struggling to put it together myself so I'm picking over other solutions to understand these and then to construct mine

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, 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!

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.