Home > Blockchain >  SwiftUI: make @ObservedObject var optional?
SwiftUI: make @ObservedObject var optional?

Time:04-29

In a view, I have something like this:

struct DriverView: View {

    @ObservedObject var car:Car?

    .....
}

I get this error:

Generic struct 'ObservedObject' requires that 'Car?' conform to 'ObservableObject'.

car is a NSManagedObject:

public class Car: NSManagedObject { }

if I remove the optional:

@ObservedObject var car:Car

the error goes away.

The problem is that I may not have a car entity to set in the DriverView at times.

How can I make car optional?

CodePudding user response:

Don't init a DriverView if you don't have a car to pass in. This can be done with an if in the body of the parent View which generates a _ConditionalView.

Note, since you are passing in a car we would normally name this a CarView.

  • Related