Lukej2680 Tech Blog

Checkpoint 4

This post covers checkpoint 4 from 100 Days of Swift - Introduction to Swift module

Description
The challenge is this: write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. That sounds easy, but there are some catches:

You can’t use Swift’s built-in sqrt() function or similar – you need to find the square root yourself. If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error. You should only consider integer square roots – don’t worry about the square root of 3 being 1.732, for example. If you can’t find the square root, throw a “no root” error.

Code

enum SquareRootError: Error {
    case integerTooSmall, integerTooLarge, squareRootNotFound
}

func originalSquareRoot(numToRoot: Int) -> Int {
    for root in 1...100 {
        if root * root == numToRoot {
            return root
        }
    }
    return 0
}

func checkPoint4(inNum: Int) throws -> Int {
    
    if inNum < 1 {
        throw SquareRootError.integerTooSmall
    } else if inNum > 10000 {
        throw SquareRootError.integerTooLarge
    } else {
        let result = originalSquareRoot(numToRoot: inNum)
        if result != 0 {
            return result
        } else {
            throw SquareRootError.squareRootNotFound
        }
    }
}

do {
    try print(checkPoint4(inNum: 25))
} catch SquareRootError.integerTooSmall {
    print("Integer must be greater then 1")
} catch SquareRootError.integerTooLarge {
    print("Integer must be less then 10000")
} catch SquareRootError.squareRootNotFound {
    print("Square Root not found")
} catch {
    print("Everything else.")
}

Explanation
I started this project off with creating an SquareRootError Enum in order to catch all the custom errors this code will be throwing.
From there I created a square root function that squares numbers from 1-100 until a square root is found. The largest integer my program will later accept is 10,000 which is why I can stop the square root function at 100. Ideally this would be optimized if input parameters were different.
If no square root is found the function returns the value 0.
My driver function accepts an integer and then will check input conditions. If they do not pass the function will throw the specified error.
From there the function runs the square root function return the result if successful or throwing the appropiate error if not.
Finally I run my driver function withing a do, try, catch syntax in order to catch errors and print appropiate error messages.

This project was taken from the HackingWithSwift website. However all code is original work by site owner.