100 Days of SwiftUI

Day 8

2026-04-25

Functions, part 2

Default values

  • I just dealt with functions in R; it has a similar syntax for defining default and using values

Errors

    1. think about what errors might happen,
    2. write a function to flag errors,
    3. handle errors raised by the function
  • this looks like a good place to use enum
  • must use the throws keyword in the function definition
  • error checking should happen as early as possible, because throwing an error will exit the function
  • Swift (not Playgrounds) require a do, try, catch pattern
  • catch can react to specific errors catch PasswordError.short {} or to general ones catch {}
  • “Pokémon Catch”?!
Gotta catch ’em all

Quizzes

  • Default parameters — 11/12
  • Writing throwing functions — 9/12
  • Running throwing functions — 5/6

Checkpoint 4

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:

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

One way is to square all of the numbers from 1 to 100 (100 * 100 = 10_000) and put them in a Set and search the Set. However, I don’t understand Set enough to know how to get the key back out once I’ve found the value

Try 2: take the number and try to use a non-calculator method? That seems fraught

Try 3: after a nap I realized that Set won’t work because of order, and Array won’t work because I still don’t know how to return the index of a found number. Brute force it is

Try 4: I tried looping through the Array and I’m not sure why indexing isn’t working.

I learned that where the statements are located in the loop is super important. The previous try with the Array might have worked if I’d had my reporting loop set up properly

enum squaresErrors: Error {
    case outOfBounds, noRoot
}

func findSquareRoot(_ number: Int) throws {

    // first check the range
    if number < 1 || number > 10_000 { throw squaresErrors.outOfBounds }

    // next do some math

    for i in 1...100 {
        if i * i == number {
            print("The square root of \(number) is \(i)")
            return
        }
    }
    throw squaresErrors.noRoot
}

do {
    try findSquareRoot(100)
} catch squaresErrors.outOfBounds {
    print("The number needs to be between 1 and 10,000")
} catch squaresErrors.noRoot {
    print("The number doesn't have an integer square root")
} catch {
    print("There was an error")
}