Printed on: September 24, 2025
Beginning with Xcode 26, there is a new strategy to observe properties of your @Observable
fashions. Prior to now, we had to make use of the withObservationTracking
perform to entry properties and obtain modifications with willSet
semantics. In Xcode 26 and Swift 6.2, we’ve entry to a completely new method that may make observing our fashions outdoors of SwiftUI a lot easier.
On this publish, we’ll check out how we will use Observations
to watch mannequin properties. We’ll additionally go over a number of the doable pitfalls and caveats related to Observations
that try to be conscious of.
Organising an commentary sequence
Swift’s new Observations
object permits us to construct an AsyncSequence
primarily based on properties of an @Observable
mannequin.
Let’s think about the next @Observable
mannequin:
@Observable
class Counter {
var depend: Int
}
For instance we would like to watch modifications to the depend
property outdoors of a SwiftUI view. Possibly we’re constructing one thing on the server or command line the place SwiftUI is not obtainable. Or perhaps you are observing this mannequin to kick off some non-UI associated course of. It actually does not matter that a lot. The purpose of this instance is that we’re having to watch our mannequin outdoors of SwiftUI’s automated monitoring of modifications to our mannequin.
To observe our Counter
with out the brand new Observations
, you’d write one thing like the next:
class CounterObserver {
let counter: Counter
init(counter: Counter) {
self.counter = counter
}
func observe() {
withObservationTracking {
print("counter.depend: (counter.depend)")
} onChange: {
self.observe()
}
}
}
This makes use of withObservationTracking
which comes with its personal caveats in addition to a fairly clunky API.
After we refactor the above to work with the brand new Observations
, we get one thing like this:
class CounterObserver {
let counter: Counter
init(counter: Counter) {
self.counter = counter
}
func observe() {
Process { [weak self] in
let values = Observations { [weak self] in
guard let self else { return 0 }
return self.counter.depend
}
for await worth in values {
guard let self else { break }
print("counter.depend: (worth)")
}
}
}
}
There are two key steps to observing modifications with Observations
:
- Organising your async sequence of noticed values
- Iterate over your commentary sequence
Let’s take a better have a look at each steps to know how they work.
Organising an async sequence of noticed values
The Observations
object that we created within the instance is an async sequence. This sequence will emit values every time a change to our mannequin’s values is detected. Notice that Observations
will solely inform us about modifications that we’re really focused on. Which means the one properties that we’re knowledgeable about are properties that we entry within the closure that we move to Observations
.
This closure additionally returns a worth. The returned worth is the worth that is emitted by the async sequence that we create.
On this case, we created our Observations
as follows:
let values = Observations { [weak self] in
guard let self else { return 0 }
return self.counter.depend
}
Which means we observe and return no matter worth our depend is.
We may additionally change our code as follows:
let values = Observations { [weak self] in
guard let self else { return "" }
return "counter.depend is (self.counter.depend)"
}
This code observes counter.depend
however our async sequence will present us with strings as an alternative of simply the counter’s worth.
There are two issues about this code that I might prefer to deal with: reminiscence administration and the output of our commentary sequence.
Let us take a look at the output first, after which we will discuss in regards to the reminiscence administration implications of utilizing Observations
.
Sequences created by Observations
will robotically observe all properties that you simply accessed in your Observations
closure. On this case we have solely accessed a single property so we’re knowledgeable every time depend
is modified. If we accessed extra properties, a change to any of the accessed properties will trigger us to obtain a brand new worth. No matter we return from Observations
is what our async sequence will output. On this case that is a string however it may be something we wish. The properties we entry do not need to be a part of our return worth. Accessing the property is sufficient to have your closure known as, even when you do not use that property to compute your return worth.
You’ve gotten in all probability seen that my Observations
closure incorporates a [weak self]
. Each time a change to our noticed properties occurs, the Observations
closure will get known as. That signifies that internally, Observations
must someway retain our closure. Because of that, we will create a retain cycle by capturing self
strongly inside an Observations
closure. To interrupt that, we must always use a weak seize.
This weak seize signifies that we’ve an non-obligatory self
to take care of. In my case, I opted to return an empty string as an alternative of nil
. That is as a result of I do not wish to need to work with an non-obligatory worth afterward in my iteration, however should you’re okay with that then there’s nothing flawed with returning nil
as an alternative of a default worth. Do word that returning a default worth doesn’t do any hurt so long as you are establishing your iteration of the async sequence accurately.
Talking of which, let’s take a better have a look at that.
Iterating over your commentary sequence
As soon as you have arrange your Observations
, you could have an async sequence you can iterate over. This sequence will output the values that you simply return out of your Observations
closure. As quickly as you begin iterating, you’ll instantly obtain the “present” worth on your commentary.
Iterating over your sequence is completed with an async for loop which is why we’re wrapping this all in a Process
:
Process { [weak self] in
let values = Observations { [weak self] in
guard let self else { return 0 }
return self.counter.depend
}
for await worth in values {
guard let self else { break }
print("counter.depend: (worth)")
}
}
Wrapping our work in a Process
, signifies that our Process
wants a [weak self]
identical to our Observations
closure does. The reason being barely totally different although. If you wish to be taught extra about reminiscence administration in duties that include async for loops, I extremely suggest you learn my publish on the subject.
When iterating over our Observations
sequence we’ll obtain values in our loop after they have been assigned to our @Observable
mannequin. Which means Observations
sequences have “did set semantics” whereas withObservationTracking
would have given us “will set semantics”.
Now that we all know in regards to the comfortable paths of Observations
, let’s discuss some caveats.
Caveats of Observations
While you observe values with Observations
, the primary and foremost caveat that I might prefer to level out is that reminiscence administration is essential to avoiding retain cycles. You have realized about this within the earlier part, and getting all of it proper may be difficult. Particularly as a result of how and whenever you unwrap self
in your Process
is crucial. Do it earlier than the for
loop and you have created a reminiscence leak that’ll run till the Observations
sequence ends (which it will not).
A second caveat that I might prefer to level out is you can miss values out of your Observable
sequence if it produces values quicker than you are consuming them.
So for instance, if we introduce a sleep
of three seconds in our loop we’ll find yourself with missed values once we produce a brand new worth each second:
for await worth in values {
guard let self else { break }
print(worth)
strive await Process.sleep(for: .seconds(3))
}
The results of sleeping on this loop whereas we produce extra values is that we are going to miss values that had been despatched throughout the sleep. Each time we obtain a brand new worth, we obtain the “present” worth and we’ll miss any values that had been despatched in between.
Often that is positive, however if you wish to course of each worth that received produced and processing may take a while, you will wish to just be sure you implement some buffering of your individual. For instance, if each produced worth would lead to a community name you’d wish to just be sure you do not await
the community name inside your loop since there is a good likelihood that you simply’d miss values whenever you try this.
Total, I believe Observations
is a big enchancment over the instruments we had earlier than Observations
got here round. Enhancements may be made within the buffering division however I believe for lots of purposes the present scenario is nice sufficient to present it a strive.