In order to have my iOS/iPadOS app working well with multiple windows, I'd like to divide app state into 'app state' (eg. data layer, state of in app purchases etc.) and 'window state' (with UI state variables specific for a single window, like isDetailViewOpen
).
Here is how I imagined it:
App.swift:
import SwiftUI
@main
struct WeathergraphApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject var appState: AppState
var body: some Scene {
WindowGroup {
ContentView(appState: appState)
}
}
}
ContentView.swift:
import SwiftUI
struct ContentView: View {
@StateObject var windowState = WindowState()
@ObservedObject var appState: AppState
var body: some View {
ZStack(alignment: Alignment.top) {
MyViewView(appState: appState, windowState: windowState)
}
.sheet(isPresented: $windowState.purchasesIsPresented) {
PurchasesView(appState: appState)
} // I am referring to windowState here, so that one window can have purchases popup open, while other won't
}
}
However, Swift won't compile my App.swift
with an error Protocol requires initializer 'init()' with type '()'
.
Any idea how to have a shared app state without resorting to singletons (or @Environment, which seems same to me)?