Why would you use @State at the application level, or anywhere outside SwiftUI?

I am trudging through the doc on the seemingly endless ways to expose model data through a view hierarchy.

The Apple doc here provides this example:

struct BookReaderApp: App {
    @State private var library = Library()

    var body: some Scene {
        WindowGroup {
            LibraryView()
                .environment(\.library, library)
        }
    }
}

Why would you do this? Is the Library at risk of being repeatedly destroyed and re-created? Also, Library is defined as an Observable class, not a struct. So why is it @State and not @StateObject?

Replies

The answers you are looking for are linked from the documentation you provided a link to, here:

https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro?language=objc

The Observable macro is new and most of the Internet hasn't caught up yet. If you can use Observable, you can use @State instead of @StateObject, even for classes and structs.

The library lives outside the App struct. Lexically, it appears to be inside the struct, but SwiftUI manages its lifetime because of that @State macro. You can put a breakpoint inside Library's init to see when it called.