Observation In SwiftUI

Hardip
levelupSwiftUI
Published in
2 min readJan 15, 2024

Observation is a new feature that was released in Swift 5.9 and facilitates the process of connecting your data models to the UI. It streamlines the way your UI responds to changes in your data, Observation makes development with SwiftUI seamless and intuitive, Observation lets you define your views or models using standard Swift syntax and use that to update the UI. Today we will cover a few topics from observation

  • What is observation?

Observation is Swift macros [allows you to generate code at compile time. This can be helpful for avoiding repetitive code, creating custom expressions, and even performing static analysis on your code] that allows you to scan any property changes in the model and update the UI accordingly.

  • Syntax:
@Observable class FoodTruckModel {    
var orders: [Order] = []
var donuts = Donut.all
}

struct DonutMenu: View {
let model: FoodTruckModel

var body: some View {
List {
Section("Donuts") {
ForEach(model.donuts) { donut in
Text(donut.name)
}
Button("Add new donut") {
model.addDonut()
}
}
}
}
}

Adding Observable is all you need to observe UI changes. You don’t need to write StateObject or ObservableObject property wrapper to the instance in view.

Is that all you need? No you need to make an import of observations to compile this new feature, so let’s add that

import Observation

Now, it will compile and if you want to see the macros behind the observation, you need to right-click on @Observable and choose the option for expend macros where you can see all the details about the macros. This is the sample output from the observable model that I wrote.

There’s more to the @observable macro than just improved syntax. SwiftUI’s internal tracking of views that access an observable class’s properties makes UI updates more effective. Better performance can be achieved with SwiftUI by removing pointless UI updates. SwiftUI can update only the necessary portions of the UI with greater accuracy and efficiency thanks to this tracking.

Using macros, like @observable, also has the advantage of abstracting away boilerplate and repetitive code. Even though the macro’s internal operations might seem magical, Xcode 15 adds the ability to expand the macro and view the generated code. To verify it, right-click on @observable and select “Expand Macro.” This visibility into the generated code can aid in troubleshooting any problems and understanding the underlying mechanics.

I appreciate you taking the time to read! Would you kindly clap, comment, and follow? Thank you so much! Knowing what kinds of content people are interested in is helpful to me. 👏🏻

--

--

Hardip
levelupSwiftUI

I breathe Swift code and live for those "app approved" emails!