How does SwiftUI find @State properties in views?

For View.onChange: refer to OpenAsyncImage/Sources/OpenAsyncImage/onChange+Backport.swift at 31aa0d53b0509f3670c17ab13130b80a99f1780d · OpenSwiftUIProject/OpenAsyncImage · GitHub

For State: refer OpenSwiftUIProject/OpenSwiftUI's State implementation which use Location system based implementation.

2 Likes

Thanks for the explanation.

It is very unintuitive (and genius at the same time) how it works! I was looking at it imperatively, and was not considering that onChange is a ViewModifier and I should think declarative.

So the only reason an API like onChange is working, is because when @State changes, view re-renders, body is called again, hence this onChange method is called with the latest L-Value of View's @State. Which now the ViewModifier can compare it with its local storage.

2 Likes

Im not sure about state, but observable object's @Published properties use a hidden feature of property wrappers, which allows you to access the parent type. I imagine @State might leverage this somehow?

I use it here to trigger objectWillChange: AsyncValue/Sources/AsyncValue/AsyncValue.swift at c04bdc325ad7f48dd2eb43bdb401c6cfaa5019e3 · BrentMifsud/AsyncValue · GitHub