How does SwiftUI know which publishers are on a view?

So I am trying to understand how it would be possible to implement something like SwiftUI, and there is one part which is currently escaping me.

So I understand at a high level that there is some kind of tree structure built out of the view hierarchy, and when an @State or @Binding attached to a view publishes a new value, the part of the tree corresponding to that publisher and its children is updated.

What I can't understand is, how is that mapping between the publisher and the node in the view hierarchy actually achieved? It seems like the @State or @Binding would only have access to its wrapped values, and not the context it is in, and there is no explicit subscription I can see taking place, so how would something like this be achieved? Is this possible in pure Swift? Would this be done through reflection? Or is there maybe some code generation being done behind the scenes to expose all the publishers of each view type?


It uses the reflection metadata emitted by the compiler to analyze the view’s stored properties.

1 Like

Is the reflection functionality available from Swift? SwiftUI uses a C++ library behind the scenes. Was that library already in use at Apple before SwiftUI was created or was it not possible to do with Swift only? If not i think it would be useful to add support for it in Swift to be able to create SwiftUI-like DSLs for other tree data structures.

My understanding is that SwiftUI uses Swift's runtime metadata directly. The only current reflection API is Mirror, is quite limited.

You can access the runtime metadata in Swift. You do not need to use C++. It just isn't exposed via a convenient API yet.

Many people have requested improved reflection APIs. Now that ABI stability has happened we're more likely to see this happen. As always, it's a matter of somebody who is capable of designing and implementing the feature deciding to invest the time necessary to do so.