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?
Here is a solution (tested with Xcode 12.1 / iOS 14.1) -
EnvironmentObject
matches injection by explicit type.