NRitH
NRitH

Reputation: 13903

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

SwiftUI errors like this appear frequently on StackOverflow:

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

The answer is always to pass a Foo instance to a view's environmentObject() function. However, this does not appear to work when passing a subclass of Foo to 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
    }
}

Is there any way to use ObservableObject subclasses as environment objects?

Upvotes: 3

Views: 368

Answers (1)

Asperi
Asperi

Reputation: 258345

Here is a solution (tested with Xcode 12.1 / iOS 14.1) - EnvironmentObject matches injection by explicit type.

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

Upvotes: 7

Related Questions