作为一名长期的 Obj-C 开发人员(从 iPhone OS 2 开始),我认为 SwiftUI 是使用 Swift 的推动力!¯\ (ツ) /¯ 因此,我仍在尝试理解一种语言如何在代码中如此类型模糊,在编译器中如此类型迂腐!!!
努力让 Swift/SwiftUI 实例化一个 UIHostingController<>,以便与 CoreData 一起使用
class MyCoreDataHostingController : UIHostingController<MyCoreDataView> {
required init?(coder: NSCoder) {//Instantiate From Storyboard
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let contentView = MyCoreDataView().environment(\.managedObjectContext, context)
super.init(coder: coder, rootView: contentView)
//Cannot convert value of type 'some View' to expected argument type 'MyCoreDataView'
}
}
struct MyCoreDataView: View {
var body: some View {
Text("Core Data View")
}
}
如何强制 Swift 推断正确/适当的类型?
到目前为止我所尝试的。
5 let contentView = MyCoreDataView()
编译/运行,但不包括 CoreData。
6 super.init(coder: coder, rootView: contentView as! MyCoreDataView)
编译,但在实例化时崩溃。
无法将 'SwiftUI.ModifiedContent<MyHostingController.MyCoreDataView, SwiftUI._EnvironmentKeyWritingModifier<__C.NSManagedObjectContext>>' (...) 类型的值转换为 'MyHostingController.MyCoreDataView' (...)。
...或者这根本不可能?(然而)