NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to use @ObservedObject to manage state from external objects

Paul Hudson    @twostraws   

Updated for Xcode 12.0

When using observed objects there are three key things we need to work with: the ObservableObject protocol is used with some sort of class that can store data, the @ObservedObject property wrapper is used inside a view to store an observable object instance, and the @Published property wrapper is added to any properties inside an observed object that should cause views to update when they change.

As an example, here’s a UserSettings class that conforms to ObservableObject:

class UserSettings: ObservableObject {
    @Published var score = 0
}

I know that doesn’t look like much code, but that’s because SwiftUI is doing a remarkable amount on our behalf! There are two things that matter in there:

  1. The ObservableObject conformance allows instances of this class to be used inside views, so that when important changes happen the view will reload.
  2. The @Published property wrapper tells SwiftUI that changes to score should trigger view reloads.

We can use that UserSettings class inside a view like this:

struct ContentView: View {
    @ObservedObject var settings = UserSettings()

    var body: some View {
        VStack {
            Text("Your score is \(settings.score)")
            Button(action: {
                self.settings.score += 1
            }) {
                Text("Increase Score")
            }
        }
    }
}

As you can see, other than using the @ObservedObject property wrapper with settings, everything else more or less looks the same – SwiftUI takes care of all the implementation details for us.

There is one important difference, though: the settings property isn’t declared as private. This is because bound objects can be used by more than one view, so it’s common to share it openly.

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

Link copied to your pasteboard.