Wednesday, February 28, 2024

Making Friends With AttributeGraph

Saagar Jha:

If you’ve used SwiftUI for long enough, you’ve probably noticed that the public Swift APIs it provides are really only half the story. Normally inconspicuous unless something goes exceedingly wrong, the private framework called AttributeGraph tracks almost every single aspect of your app from behind the scenes to make decisions on when things need to be updated. It would not be much of an exaggeration to suggest that this C++ library is actually what runs the show, with SwiftUI just being a thin veneer on top to draw some platform-appropriate controls and provide a stable interface to program against. True to its name, AttributeGraph provides the foundation of what a declarative UI framework needs: a graph of attributes that tracks data dependencies.

Mastering how these dependencies work is crucial to writing advanced SwiftUI code. Unfortunately, being a private implementation detail of a closed-source framework means that searching for AttributeGraph online usually only yields results from people desperate for help with their crashes.


Shortly before a view’s body is computed, it goes through and sets the _location on all relevant State variables, so that they are ready for dependency tracking. Typically, a property wrapper does not have the ability to grab context from outside of itself (for example, by looking up who owns it). SwiftUI can use reflection much like we did to discover State members that it needs to install _location on, sidestepping this issue. To discover State in nested types, it needs a little bit of help: this is why we had to add a DynamicProperty conformance earlier. In that case, it uses reflection to look for DynamicProperty members instead and then does a search for State inside of those.


Comments RSS · Twitter · Mastodon

Leave a Comment