NEW: Join my free 100 Days of SwiftUI challenge today! >>

What is the @Published property wrapper?

Paul Hudson    @twostraws   

Fully updated for Xcode 11 GM

@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.

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!