Fatal error: @SceneStorage is only for use with SwiftUI App Lifecycle.: file SwiftUI, line 0

Fatal error: @SceneStorage is only for use with SwiftUI App Lifecycle.: file SwiftUI, line 0

我正在尝试为 iOS 14“SceneStorage”使用新的 属性 包装器,尽管它会产生此错误:

Fatal error: @SceneStorage is only for use with SwiftUI App Lifecycle.: file SwiftUI, line 0

这是我的代码:

struct ContentView: View {
    @SceneStorage("isLoggedIn") var isLoggedIn = true
    
    var body: some View {
        Text("Hello, World!).onAppear {
            print($isLoggedIn)
        }
    }
}

已更新.... 谢谢,@Asperi! 确保将 Life Cycle 设置为 SwiftUI App

适用于 Xcode 12 / iOS 14 / SwiftUI 生命周期

您的项目似乎使用了 SwiftUI 1.0 AppDelegate/SceneDelegate(又名 UIKit 生命周期)

在 SwiftUI 生命周期中,您的应用程序主程序应该像

@main
struct YourAppName: App {
    var body: some Scene {
        WindowGroup {       // << this introduces Scene, needed for SceneStorage
            ContentView()
        }
    }
}