Thursday, April 27, 2023

Apple’s Guidance for StateObject Initialization

Jordan Morgan (Mastodon):

In an attempt to put an end to our StateObject woes in a more paradigmatic manner, Luca Bernardi let us know that Apple’s official documentation now tackles the matter. Specifically, there is now text detailing how to handle dependency injection with StateObject. This is exactly the kind of material we need from Apple, and it clears up a lot of confusion and advice I’ve been reading.


SwiftUI only will initialize a state object the first time you call it within its view.


All of this basically boils down to - dependency injection with state object initialization works great if parties outside of the view housing it are feeding it data that doesn’t change either.


If you did need the autoclosure to fire again, you could set the identity of the view to the value you’re interested in. […] Since the state object isn’t recreated when view inputs are changed (and it certainly shouldn’t), but when the view’s identity changes, this route forces the initializer to run again. But again, I can’t really see this being a viable route for most projects.


1 Comment RSS · Twitter · Mastodon

Remember the good old days, when the main documentation page could be sorted by date descending, so you didn’t have to follow random Apple engineers on social media to know what was new or updated?

(This page:

Leave a Comment