Thanks for getting back to me.
I'm thinking specifically about the instantiation of a manager-style class that is global to the app and placed into the environment at launch time. The documentation that you linked to gives this specific example:
@main
struct BookReaderApp: App {
@State private var library = Library()
var body: some Scene {
WindowGroup {
LibraryView()
.environment(library)
}
}
}
In the example, the Library class is created as a @State var and put into the environment. My first question (which is more theoretical) is: Why does the variable need to be annotated with @State. My (perhaps naive) assumption was that the App struct is special and is initialized only once, so it's not immediately obvious to me why its properties need to be held in state. Indeed, making it a let constant without the @State annotation seems to result in the same behavior.
My second, more practical question is: What is the correct way to manually instantiate the Library (rather than doing so in the property declarations). There are various reasons why you might want to do this, but for the sake of example, I'm thinking of something along these lines:
@main
struct BookReaderApp: App {
@State private var library
init() {
let thing = Thing()
self.library = Library(thing: thing)
}
var body: some Scene {
WindowGroup {
LibraryView()
.environment(library)
}
}
}
Note that in this case, Library is not created in the property declarations, but in the init. Searching around on GitHub, I find some examples where people do:
self.library = Library(thing: thing)
and other cases where people do:
self._library = State(initialValue: Library(thing: thing))
I'm trying to understand what the difference is between these two (if anything).
Thanks for any light you can shed on these (possibly newbie) questions!
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: