WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to find which data change is causing a SwiftUI view to update

Paul Hudson    @twostraws   

Updated for Xcode 14.2

SwiftUI provides a special, debug-only method call we can use to identify what change caused a view to reload itself. The method is specifically for debugging, and should not be shipped in a real app, but it’s extremely helpful for the times when you can see a view is reinvoking its body property but you’re not sure why.

The method is Self._printChanges(), and should be called inside the body property. This means you may temporarily need to add an explicit return to send back your regular view code.

To demonstrate this method in action, here’s some sample code where a view relies on an observable object that randomly issues change notifications:

class EvilStateObject: ObservableObject {
    var timer: Timer?

    init() {
        timer = Timer.scheduledTimer(
            withTimeInterval: 1,
            repeats: true
        ) { _ in
            if Int.random(in: 1...5) == 1 {
                self.objectWillChange.send()
            }
        }
    }
}

struct ContentView: View {
    @StateObject private var evilObject = EvilStateObject()

    var body: some View {
        let _ = Self._printChanges()
        Text("What could possibly go wrong?")
    }
}

Peter Steinberger has a helpful tip for discovering when the body property of a view is being reinvoked: assign a random background color to one of its views. This will be re-evaluated along with the rest of the body, so if body is being called a lot then your views will flicker as they change background.

To use this in your own projects, first add the following Color extension to get random colors:

extension ShapeStyle where Self == Color {
    static var random: Color {
        Color(
            red: .random(in: 0...1),
            green: .random(in: 0...1),
            blue: .random(in: 0...1)
        )
    }
}

And now go ahead and use it with background() whenever you’re curious what’s happening:

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .background(.random)
    }
}

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.