100 Days of SwiftUI
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
structto a variable in thestructunless you identify it asmutating - if you use a
mutating structyou can’t assign an instance (record) to a constant - calling a
structis like calling afunc - Inside a
structthere are properties and methods; calling thestructwith 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
structI havevar score: {score += 10}it will automatically increase the submittedscoreby 10? - Nope. At least not in his example
- Guessing here: In my
- it is kinda the opposite to what I thought — every time you call the instance parameter it does the calculation
- now we’ve got
getandsetwithin 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
willsetanddidsetmake sense when I’m watching but I’m not sure they will when I’m trying- to avoid performance problems, don’t make the n
sets 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
selfis 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