100 Days of SwiftUI Day 9

100 Days of SwiftUI – Day 9 – Closures

We were warned yesterday that today would be really, really difficult. They weren’t kidding. After expanding on functions during day 8, today, we learned about closures in SwiftUI. Instead of a single hour, I put in about 4 hours because I had a hard time grasping everything that was being taught. As such, today’s recap will be a bit short. Nonetheless, let’s dive in!

How to use and create closures in SwiftUI

A closure in SwiftUI allows us to skip creating a function and instead directly assign functionality to a variable or constant. There are many possible benefits to this, so if you want to learn more, I strongly encourage you to take some time and read Paul’s explanation on closures.

// Creating basic closures

let simplePrint = {
    print("This is a simple closure, without a return or parameter")
}

simplePrint()

// Creating a closure with parameter and no return

let closureWithParameters = { (name: String) in
    print("My name is \(name).")
}

closureWithParameters("Maverick")

Trailing closures and shorthand syntax

Swift features a few neat shorthands to reduce the amount of code you have to write to use closures. This saves time and helps keep your code a bit more organised. Here’s a few examples:

let myTeam = ["Rowby", "James", "Mikuru", "Fallon", "Michael"].sorted()
print(myTeam)

// Shorthand syntax closure to reverse sort myTeam.
let reverseTeam = myTeam.sorted { $0 > $1 }

print(reverseTeam)

// Shorthand syntax closure to filter out names that start with an "M" in myTeam.
let myFilteredTeam = myTeam.filter { $0.hasPrefix("M") }
print(myFilteredTeam

Accepting functions as parameters

Last but not least for today’s learning material is how to use a function as a parameter. Why would you possibly want this? Well, Paul thought we might’ve asked ourselves that.

func doImportantWork(first: () -> Void, second: () -> Void, third: () -> Void) {
    print("Starting first work...")
    first()
    print("Starting second work...")
    second()
    print("Starting third work...")
    third()
    print("Done!")
}

doImportantWork {
    print("This is the first work!")
} second: {
    print("This is the second work!")
} third: {
    print("This is the third work!")
}

SwiftUI checkpoint 5

Perhaps it was because I had already been following along and rewatching today’s videos for hours, but this challenge had me frustrated. I was making things more difficult in my head by the minute, until I finally figured out that I was trying to force every single thing we learned today into the solution, which was not at all necessary. The assignment was:

Use the following array of integers:

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

And then, while not using temporary variables or constants:

  1. Filter out any numbers that are even
  2. Sort the array in ascending order
  3. Map them to strings in the format “7 is a lucky number”
  4. Print the resulting array, one item per line

It took me a long while of trying various possible solutions and going back over the video’s, but this is the final solution I came up with:

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

let solveCheckpoint = { (array: [Int]) in
    array.filter { $0 % 2 != 0 }
        .sorted { $1 > $0 }
        .map { print("\($0) is a lucky number!") }
}

solveCheckpoint(luckyNumbers)

And that’s it for day 9! It was a very difficult day and I feel I’ll need to refer to this day again in the future to ensure I understand all we’ve learned completely. Tomorrow, we’ll learn about structs, computed properties, and property observers. Onwards we go!

Darryl

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

3 Comments

  • Hey Darryl, thank you for sharing your results, I was frustrated as well with my results, always missing something to complete the Checkpoint 5, but now is all coming together!

    • Hi Carlos, you’re welcome! Hopefully they’ve helped you a bit. The frustration is part of learning haha. It’ll get more difficult as the days of the course go by, but keep at it. There’s no shame in skipping a challenge and coming back at a later day with a fresh look on things!

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 29 – Word Scramble

100 Days of SwiftUI – Day 88

100 Days of SwiftUI – Day 39 – Moonshot

100 Days of SwiftUI – Day 86