Home > Back-end >  My class conforms to ObservableObject but somehow swift compiler does not think so
My class conforms to ObservableObject but somehow swift compiler does not think so

Time:10-24

protocol ErrorableViewProtocol: View {
    var error: Error? { get set }
}

class ObservableError: ObservableObject {
    @Published var error: Error?
}

struct ErrorableView<T: ErrorableViewProtocol>: View {
    var errorable: T
    
    var body: some View {
        if let error = errorable.error {
            ErrorView(error: error)
        } else {
            errorable
        }
    }
}

enter image description here

Where did I stray off the righeous path?

CodePudding user response:

ObservableError conforms to ObservableObject. You can't say the same about Optional<ObservableError> (aka ObservableError?). When you use @StateObject, you should always instantiate the class in the same struct.

However, when you want to pass in an object from another struct, use @ObservedObject.

  • Related