NEW: Nominations are now open for the 2019 Swift Community Awards! >>

How to use @ObservedObject to manage state from external objects

Paul Hudson    @twostraws   

Fully updated for Xcode 11.1

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.

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Similar solutions…

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5