Photo by Mario Heller on Unsplash

Migrating From Observable Object to Observable

Ash Slone
Bilue Product Design & Technology Blog
2 min readFeb 26, 2024

--

Last year, 2023, with Apple’s release of iOS 17, iPadOS 17, macOS 14, tvOS 17, and watchOS 10, there is a new way to be able to perform Observation in SwiftUI. This brought in a lot of quality of life improvements for the code when compared to the old way of Observable Objects. We will dive into those improvements and how we can migrate to the new Observable macro.

Quality of Life Improvements

When we were stuck with Observable Objects we were limited in what all we could track. Now with the introduction of this new Observable macro, we can also track optionals and collections of objects.

Migration to Observable Macro

To get started we need to replace ObservableObject with the new Observable macro. If you’re unfamiliar with the concept of a macro (see more) it just generates code at compile time. It’s a super easy and straightforward migration to do.

Before

After

Now prior we were having to use the Published macro to let any observers know that the data has changed. Now we don’t have to use this macro.

Before

After

So now if we wanted to use this ViewModel object in our SwiftUI view we can and this has changed slightly as well. We no longer need the ObservedObject macro in our view.

Before

After

However if in the instance of this text property needing to be used as a binding such as in TextField we need to give the ViewModel a new macro called Bindable.

Before

After

Wrap Up

As you can see the new concise way of working with observable objects has been a huge quality of life improvement with very little changes overall. One last thing, we can still use ObservedObject and Observable together so this lets us incrementally migrate to this new pattern.

Happy coding!

--

--