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

SOLVED: Help with Checkpoint 4

Forums > 100 Days of SwiftUI

In this checkpoint I have to create a function that finds the square root of a number and returns it without using sqrt() or similar methods. As per the hint in the course, I brute forced all the possible square roots with a for loop that checks if the input is equal to i * i and then breaks if it gets a match. But I can't figure out how to return the value of 'i' as an integer in the function. Would appreciate any help.

enum numberError: Error {
    case outOfBounds, noRoot
}

func checkSquareRoot(_ number: Int) throws -> Int {
    if number < 1 || number > 10_000 {
        throw numberError.outOfBounds
    }

    for i in 1...100 {
        if number == i * i {
            let root = i
            break
        } else {
            throw numberError.noRoot
        }
    }
    return root
    // How do I return the value of root / i ?
}

let integer = 25

do {
    let result = try checkSquareRoot(integer)
    print("Square root of \(integer) is \(result).")
} catch numberError.outOfBounds {
    print("\(integer) is out of bounds")
} catch numberError.noRoot {
    print("\(integer) is not a perfect square root.")
} catch {
    print("Error.")
}

5      

Found a workaround! It's not perfect but the code runs correctly.

import Cocoa

enum numberError: Error {
    case outOfBounds, noRoot
}

func checkSquareRoot(_ number: Int) throws -> Int {
    if number < 1 || number > 10_000 {
        throw numberError.outOfBounds
    }

    var root = 0 // initializes a variable to store and return the result of the loop.

    for i in 1...100 {
        if number == i * i {
            root = i // assignes the value of i to root
            break
        }
    }

    if root == 0 { // if root hasn't received a new value, throws an error.
        throw numberError.noRoot
    }

    return root
}

let input = 100

do {
    let result = try checkSquareRoot(input)
    print("Square root of \(input) is \(result).")
} catch numberError.outOfBounds {
    print("\(input) is out of bounds")
} catch numberError.noRoot {
    print("\(input) is not a perfect square root.")
} catch {
    print("Error.")
}

The only problem I see is throwing the numberError.noRoot. Is there a more elegant way to do this? If I put it in the loop as an 'else' it would just throw an error after the first iteration if the square root isn't 1.

3      

You can just return i from within your loop.

As for throwing noRoot, do that after running through the entire loop without a hit.

2      

Instead of break return i.

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

and delete return root

enum numberError: Error {
    case outOfBounds, noRoot
}

func checkSquareRoot(_ number: Int) throws -> Int {
    if number < 1 || number > 10_000 {
        throw numberError.outOfBounds
    }

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

    throw numberError.noRoot
}

let input = 100

do {
    let result = try checkSquareRoot(input)
    print("Square root of \(input) is \(result).")
} catch numberError.outOfBounds {
    print("\(input) is out of bounds")
} catch numberError.noRoot {
    print("\(input) is not a perfect square root.")
} catch {
    print("Error.")
}

6      

Wow! It was so easy. For some reason when I tried returning i inside the loop Xcode complained so I just gave up on it. Thanks for the help!

3      

Wow thank you both!

2      

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

the return i doesnt make the program out of the loop, it still doing the loop until reach 100. For me I prefer with break inside the loop so the program dont waste any more time.

2      

Change the for loop in the above code to this:

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

and you will see that the loop only runs 10 times before hitting a match and causing the function to return.

playground loop output

return will cause the loop to exit the function early.

4      

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.