SwiftUI:找不到类型 Y 的 ObservableObject,其中 Y 是 ObservableObject 的子类

SwiftUI: No ObservableObject of type Y found, where Y is a subclass of an ObservableObject

像这样的 SwiftUI 错误经常出现在 Whosebug 上:

Thread 1: Fatal error: No ObservableObject of type Foo found. A View.environmentObject(_:) for Foo may be missing as an ancestor of this view.

答案始终是将 Foo 实例传递给视图的 environmentObject() 函数。但是,当将 Foo 子类 传递给 environmentObject().

时,这似乎不起作用

Foo.swift

class Foo: ObservableObject {
    func doSomething() { ... }
}

Bar.swift

class Bar: Foo {
    override func doSomething() { ... }
}

Views.swift

struct BrokenView: View {
    @EnvironmentObject var foo: Foo

    var body: some View { ... }
}

struct WorkingView: View {
    @EnvironmentObject var foo: Bar

    var body: some View { ... }
}

struct ParentView: View {
    var body: some View {
        BrokenView().environmentObject(Bar())   // No ObservableObject of type Foo found...
        WorkingView().environmentObject(Bar())  // OK
    }
}

有什么方法可以使用 ObservableObject 子类作为环境对象吗?

这是一个解决方案(使用 Xcode 12.1 / iOS 14.1 测试)- EnvironmentObject 通过显式类型匹配注入。

var body: some View {
    BrokenView().environmentObject(Bar() as Foo)   // OK
    WorkingView().environmentObject(Bar())  // OK
}