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

How to send state updates manually using objectWillChange

Paul Hudson    @twostraws   

Fully updated for Xcode 11.1

Although using @Published is the easiest way to control state updates, you can also do it by hand if you need something specific. For example, you might want the view to refresh only if you’re happy with the values you’ve been given.

Using this approach takes three steps: importing the Combine framework, adding a publisher, then using the publisher. Publishers are Combine’s way of announcing changes to whatever is watching, which in the case of SwiftUI is zero or more views.

Here’s an example in code:

import Combine
import SwiftUI

class UserAuthentication: ObservableObject {
    let objectWillChange = ObservableObjectPublisher()

    var username = "" {
        willSet {
            objectWillChange.send()
        }
    }
}

Let’s break down the code, to make it easier to understand. First, we have this:

let objectWillChange = ObservableObjectPublisher()

That creates an objectWillChange property as an instance of ObservableObjetPublisher. This comes from the Combine framework, which is why you need to add import Combine to make your code compile. The job of an observable object publisher is simple: whenever we want to tell the world that our object has changed, we ask the publisher to do it for us.

Second, we have a willSet property observer attached to the username property of UserAuthentication so that we can run code whenever that value changes. In our example code, we call objectWillChange.send() whenever username changes, which is what tells the objectWillChange publisher to put out the news that our data has changed so that any subscribed views can refresh.

As our UserAuthentication class conforms to ObservableObject, we can use it just like any other @ObservedObject property. So, we might use it like this to display the user’s entry as they type, like this:

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

    var body: some View {
        VStack {
            TextField("Username", text: $settings.username)
                .textFieldStyle(RoundedBorderTextFieldStyle())

            Text("Your username is: \(settings.username)")
        }
    }
}

Note: SwiftUI actually provides us with a default objectWillChange property, but it doesn’t actually work in the current beta. So, it’s important to declare your own with the same name.

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

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: 4.8/5