Is it intended for onchange to work with let properties?

Hi all,

by chance, we introduced code similar to the following in the body of one of our views:

struct MyView: View {
    let myInt: Int

    var body: some View {
        EmptyView() // Empty body
            .onChange(of: myInt) { newValue in
                …
            }
    }
}

Notice that a simple let of type Int is used here, rather than State or something similar. While it works, I’d like to clarify a few things:

  • Is this behavior actually expected and reliable, or is it a gray area and can be changed in the future?
  • If it is expected, can this be made clearer in the documentation?
  • If it is a gray area, can the documentation be improved to address it?

Thanks!

1 Like

I mean the value never changes, so it doesn’t make sense to use here, but nevertheless it is valid Swift code. If Apple ever changes the signature, we don’t know, but I don’t see any reason for this.

Sorry if I didn’t make it clear in the original post. By "it works," I didn’t just mean that it compiles—I meant that onChange is actually triggered when views are rebuilt in such scenarios. My question is whether this behavior is intentional from the framework side (SwiftUI, not Swift as a language). If so, can this be made clearer in the documentation?

The behavior and documentation of the SwiftUI framework is a topic for the Apple Developer Forums, not this forum.