如何解决错误"Result of call to environment is unused"?


let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
// Add `@Environment(.managedObjectContext)` in the views that will need the context.
let loginView = LoginView().environmentObject(GlobalEnviroment())
loginView.environment(.managedObjectContext, context)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: loginView)
self.window = window
window.makeKeyAndVisible()
}
}

.environment返回一个已将环境传递到其中的View的修改版本。您需要实际保留/使用该函数的结果。

最简单的方法就是把它和你已经拥有的东西联系起来。

let loginView = LoginView()
.environmentObject(GlobalEnviroment())
.environment(.managedObjectContext, context)
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: loginView)
self.window = window
window.makeKeyAndVisible()
}

相关内容

最新更新