What is @Published in SwiftUI?

Dec 29, 2020 1 min read
What is @Published in SwiftUI?

@Published is one of the most useful property wrappers in SwiftUI, allowing us to create observable objects that automatically announce when changes occur. SwiftUI will automatically monitor for such changes, and re-invoke the body property of any views that rely on the data. In practical terms, that means whenever an object with a property marked @Published is changed, all views using that object will be reloaded to reflect those changes.

For example, if we have an observable object such as this one:

class Bag: ObservableObject {
    var items = [String]()
}

That conforms to the ObservableObject protocol, which means SwiftUI’s views can watch it for changes. But because its only property isn’t marked with @Published, no change announcements will ever be sent – you can add items to the array freely and no views will update.

If you wanted change announcements to be sent whenever something was added or removed from items, you would mark it with @Published, like this:

class Bag: ObservableObject {
    @Published var items = [String]()
}

You don’t need to do anything else – the @Published property wrapper effectively adds a willSet property observer to items, so that any changes are automatically sent out to observers.

As you can see, @Published is opt-in – you need to list which properties should cause announcements, because the default is that changes don’t cause reloads. This means you can have properties that store caches, properties for internal use, and more, and they won’t force SwiftUI to reload views when they change unless you specifically mark them with @Published.

Example Code:

class DataSource: ObservableObject {
  @Published var names = [String]()
}

struct NamesList: View {
  @ObservedObject var dataSource: DataSource

  var body: some View {
    List(dataSource.names, id: \.self) { name in
      Text(name)
    }
  }
}

Source: hackingwithswift

Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.