a chalkboard with some writing on it

100 Days of SwiftUI – Day 7 & Day 8

Functions are fundamental to software development, so today we learn about them before moving on to basic error handling.

DRY programming is a concept I remember from university – Don’t Repeat Yourself. And so, in Day 7, we come to functions in Swift. I also recently heard one of the developers in my team referring jokingly to WET programming, which was new to me. Turns out that means Write Everything Twice! 🤣

Anyway, this is all easy enough to understand. I’m pretty familiar with functions, parameters, returning values etc etc so I can steam through this section without to much trouble.

On Day 8 we come to throwing and catching errors. This is something I’m aware of but less familiar with. Swift requires you to create an enum to define your error cases and then call any throwing functions within a do-catch block which specifies how to handle different error cases. It’s not hard, but I decide to spend a little extra time going through this section carefully as it’s new to me.

Checkpoint 4

We now need to put our new skills with functions and error handling to good use in Checkpoint 4. The task this time is to create a function which finds and prints the integer square root of a given integer between 1 and 10,000. If there isn’t one, or if the user supplies a number outside that range, we’re to throw an error and print a suitable message.

This task is not hard but it does require a bit of thought as to how to implement the function. The first hint on the checkpoint page gave me the clue I needed about how to solve this in the end, and then it was just about handling the errors.

// Error cases
enum SqrtError: Error {
    case outOfBounds, noRoot
}

func findSqrt(of number: Int) throws -> Int {
    // Return an error if number is < 1 and > 10,000
    if number < 1 || number > 10000 {
        throw SqrtError.outOfBounds
    }
    
    // Check if the given number equals any intger squared
    for i in 1...100 {
        // If so, return that integer
        if i * i == number {
            return i
        }
    }
    
    // No integer squared = number so no root
    throw SqrtError.noRoot
}

// Try it out
do {
    try print(findSqrt(of: 4))
} catch SqrtError.outOfBounds {
    print("Number must be an integer between 1 and 10,000")
} catch SqrtError.noRoot {
    print("This number doesn't have an integer square root")
} catch {
    print("Something went wrong: \(error.localizedDescription)")
}