100 Days of SwiftUI

Day 10

2026-04-27

Structs, part 1

“Struct”? Is this “Construct” or “Structure”? Both? Neither?

Wikipedia informs me it’s “Structure” from Algol 68

How to create your own structs

  • “Structs let us create our own complex data types”
  • The example makes it look like a record
heh, not an album but a database-type record
struct Album {
    let title: String
    let artist: String
    let year: Int

    func printSummary() {
        print("\(title) (\(year)) by \(artist)")
    }
}
  • Convention: use capital initial + camel case for data types and lower initial + camel case for something inside the type
  • remember to add data in the order it was defined
  • you can’t write data from inside a struct to a variable in the struct unless you identify it as mutating
  • if you use a mutating struct you can’t assign an instance (record) to a constant
  • calling a struct is like calling a func
  • Inside a struct there are properties and methods; calling the struct with data creates an instance of it and initializes the instance
  • Methods belong to a type; functions do not

How to compute property values dynamically

  • computed properties are a blend of stored properties and functions.
    • Guessing here: In my struct I have var score: {score += 10} it will automatically increase the submitted score by 10?
    • Nope. At least not in his example
  • it is kinda the opposite to what I thought — every time you call the instance parameter it does the calculation
  • now we’ve got get and set within the dynamic property and it’s starting to get confusing
not even sure that is valid

a computed property is effectively just a function call that happens to belong to your struct

How to take action when a property changes

  • property observers this is all new ground for me
  • willset and didset make sense when I’m watching but I’m not sure they will when I’m trying
  • to avoid performance problems, don’t make the nsets too complicated

How to create custom initializers

  • all properties must have a value by the time the initializer ends
  • “memberwise” ➝ accepts each property in the order it was defined in the struct
  • Swift removes the built-in memberwise initiator if you create your own unless you take steps to avoid that
  • self is for the instance

Quizzes

  • Structs — 8/12 — 💩
  • Mutating methods — 9/12
  • Computed properties — 10/12
  • Property observers — 9/12
  • Initializers — 8/12
  • Referring to the current instance — 9/12 — I’m still mixing up internal vs external properties
punctuation is gonna be my downfall