Protocol Decorated with ObservableObject

Viewed 79

I created a protocol JSONService that conforms to the ObservableObject.

protocol JSONService {
    var screenModel: ScreenModel? { get set }
    func load(_ resourceName: String) async throws 
}

Next, I created the LocalService which conforms to the ObservableObject as shown below:

class LocalService: JSONService, ObservableObject {
    
    @Published var screenModel: ScreenModel?
    
    func load(_ resourceName: String) async throws {
        
        // some code
        
    }
    
}

Now, when I created a property in my View (SwiftUI) then I get an error:

struct ContentView: View {
    
    @StateObject private var jsonService: any JSONService

Type 'any JSONService' cannot conform to 'ObservableObject'

How can I use @StateObject with protocols?

1 Answers

You just add the conformance to the protocol.

protocol JSONService: ObservableObject, AnyObject {
    var screenModel: ScreenModel? { get set }
    func load(_ resourceName: String) async throws
}

Then you can add the generic to the View

struct GenericOOView<JS: JSONService>: View {
    @StateObject private var jsonService: JS
    
    init(jsonService: JS){
        _jsonService = StateObject(wrappedValue: jsonService)
    }

    var body: some View {
        Text("Hello, World!")
    }
}
Related