100 Days of SwiftUI

Day 9

2026-04-26

This one looks like a lot, first we have the warning

Closures are really difficult.

You don’t say!

and then there are 6 quizzes and a Checkpoint. Seems like a lot for 1 day, but we’ll see how it goes.

Closures

How to create and use closures

  • I can already see that syntax, especially wrt punctuation, is going to be a pain
  • Parameters, if needed, go inside the { } and use the keyword in
  • They are used A Lot
  • Functions have types and they only care about what types of data are coming in and going out
    • this means that names are not part of the function’s type so if you use a copy (or create a closure) of a function then you don’t add any parameter names (so confusing)
  • “If you’re finding it hard, it means things are working normally.”
  • I get the impression that Closures might be more useful for 1-off customizations of (built-in) functions, where standalone functions would be better for oft-repeated code

How to use trailing closures and shorthand syntax

  • If the closure your using requires, say 2 Strings and outputs a Bool then you don’t have to specify them
  • You also can remove some more syntax e.g. x.sorted(by: {closure}) becomes x.sorted {closure}
  • ugh $0 $1 really? I mean, I suppose… I understand “less cluttered” but it could make things more confusing

How to accept functions as parameters

  • turtles all the way down
  • important to SwiftUI
  • This is going to take a while for me to understand

Quizzes

  • Creating basic closures — 10/12
  • Accepting parameters in a closure — 10/12
  • Returning values from a closure — 10/12
  • Shorthand parameter names — 6/6
  • Closures as parameters — 6/12 — ooof parameters are hard
  • Trailing closure syntax — 12/12

Checkpoint 5

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

  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

You’ve already met sorted(), filter(), map(), so I’d like you to put them together in a chain – call one, then the other, then the other back to back without using temporary variables.

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

// filter first

luckyNumbers.filter {!$0.isMultiple(of: 2)}

// add the sort

luckyNumbers.filter {!$0.isMultiple(of: 2)}.sorted()

// add the map

luckyNumbers.filter {!$0.isMultiple(of: 2)}.sorted().map {print("\($0) is a lucky number")}