I'm using @EnvironmentObject
like this:
struct MyView: View {
@EnvironmentObject var object: MyObject
...
}
but my code doesn't need there to be a value for object
.
Just making this optional doesn't work (doesn't even compile - Property type 'MyObject?' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'
)
You also can't pass in a default object (that would solve my problem too) - either as an initial value to the property, or as a parameter to @EnvironmentObject
. e.i. these don't work:
@EnvironmentObject var object: MyObject = MyObject()
@EnvironmentObject(MyObject()) var object: MyObject
I've tried to wrap the @EnvironmentObject
in my own property wrapper, but that just doesn't work at all.
I've also tried wrapping accesses to the object property, but it doesn't throw an exception which can be caught, it throws a fatalError
.
Is there anything I'm missing, or am I just trying the impossible?
@EnvironmentObject
? Why don't just use instead@ObjservedObject
which can have and default instance and be optional?