WWDC 2023: Discover Observation in SwiftUI
Observation Design Pattern? Maybe
For the purposes of using the WWDC video I wanted complete code. This article provides that, but is not intended to be a replacement for the code in https://developer.apple.com/videos/play/wwdc2023/10149/?time=473 and I recommend you watch that video. This Medium article requires Xcode 15 to be running.
What is observation?
Observation has been added to Swift for tracking changes to properties, and uses macros to do so. Adding @Observable allows us to make the UI respond to data models.
The simple example:
@Observable class FoodTruckModel {
var orders: [Order] = []
var donuts = Donut.all
}
We have code here which means that the properties orders and donuts are effectively @Published types.
The example
There is a food truck example in the video. Unfortunately on it’s own it cannot run.
They call this a simple example. When the body is executed SwiftUI knows it access donuts, so if the property is changed the system knows to re-render the view.
@Observable class FoodTruckModel {
var orders: [Order] = []
var donuts = Donut.all
}
struct DonutMenu: View…