100 Days of SwiftUI Day 8

100 Days of SwiftUI – Day 8 – Functions Part 2

We’ve arrived at the second week of our 100 days of SwiftUI course. Yesterday, we learned how to reuse our code with functions. Today, we’re expanding on functions by using default parameters and learning how to handle possible errors in our code. Let’s dive in!

Using default parameters in functions

When adding parameters to a function, we tell Swift that, whenever that function is called, we’ll pass on values for the parameters we’ve set. Sometimes, however, a function may need to use the same value for a parameter more often than not. In those cases, wouldn’t it be easier to specify that value in the function itself, instead of having to pass on that value every single time the function is called?

That’s where default parameters come in!

// Function that rolls a dice with the number of sides passed on as value
func noDefaultParameter(sides: Int) {
    let diceRoll = Int.random(in: 1...sides)
    print("The number we've rolled is \(diceRoll). We rolled a \(sides) sided dice")

noDefaultParameter(sides: 20)

// Function that rolls a 6 sided dice by default, unless we pass on another value in the function call
func defaultParameter(sides: Int = 6) {
    let diceRoll = Int.random(in: 1...sides)
    print("The number we've rolled is \(diceRoll). We rolled a \(sides) sided dice")


Handling errors in functions

Whenever an error pops up in one of our functions, Swift will force us to either handle the error or at least acknowledge that it might happen. This takes three steps:

  1. Define all the errors that might happen in the code we’re writing
  2. Write a function that runs normally but can throw an error if one occurs
  3. Try and run the function and handle (catch) any errors that come back

Here’s a simple example I came up with.

// Create an enum with cases for each error
enum additionError : Error {
    case numberTooLow, numberTooHigh

// Create a function that can throw an error
func simpleAddition(firstNumber number1: Int, secondNumber number2: Int) throws -> Int  {
    if number1 < 0 {
        throw additionError.numberTooLow
    } else if number2 > 100_000_000 {
        throw additionError.numberTooHigh
    let addition = number1 + number2
    return addition

// Do, try, catch block. Try to run the code and if need be, catch the errors that pop up.

do {
    let additionResult = try(simpleAddition(firstNumber: -12, secondNumber: 32))
    print("The result of the addition is \(additionResult)")
} catch additionError.numberTooLow {
    print("Error! That number is too low. Please enter 0 or higher.")
} catch additionError.numberTooHigh {
    print("Error! That number is too high. Please enter a number less than 100.000.000.")
} catch {
    print("There was an unknown error, sorry about that!")

If you’re interested in learning when to use the throwing function, check out this article by Paul.

SwiftUI checkpoint 4

We finished day 8 with the fourth checkpoint of the course. Now that we have added functions to our list of skills, it was time to put those skills to the test. The assignment:

Write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. Of course, there are some important 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.

My biggest struggle with this challenge was figuring out how to calculate the square root of a number. I’m generally bad at this type of math, but once I figured it out, the remainder of the challenge was quite doable!

Here’s the solution I came up with.

enum squarerootError : Error {
    case outOfBoundsTooHigh, outOfBoundsTooLow, noRoot

func calcSqrt(squareroot number: Int) throws -> Int {
    if number < 1 {
        throw squarerootError.outOfBoundsTooLow
    } else if number > 10000 {
        throw squarerootError.outOfBoundsTooHigh
    for i in 1...10000 {
        if i * i == number {
            return i
    throw squarerootError.noRoot

var number = 25

do {
    let result = try calcSqrt(squareroot: number)
    print("The squareroot of \(number) is \(result)")
} catch squarerootError.noRoot {
    print("No square root found!")
} catch squarerootError.outOfBoundsTooLow {
    print("Error! Pick a number above 1.")
} catch squarerootError.outOfBoundsTooHigh {
    print("Error! Pick a number below 10000.")
} catch {
    print("There was an error.")

And that’s it for day 8! Let me know what you think of my solution. I’m sure there are things that I could’ve done differently, but this was the best solution I could come up with and it did the job. Tomorrow, we’re diving into closures. I’ve already seen warning signs that they are really difficult to grasp, so I’m trying to go in well rested and ready. Onwards we go.


Hi! My name is Darryl and this is my personal blog where I write about my journey as I learn programming! You'll also find articles about other things that interest me including games, tech and anime.

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

100 Days of SwiftUI – Day 21 – Design

100 Days of SwiftUI – Day 4 – Type Annotations

100 Days of SwiftUI – Day 68

100 Days of SwiftUI – Day 46