1

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?

Mary Doe
  • 1,073
  • 1
  • 6
  • 22

1 Answers1

1

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!")
    }
}
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
  • I am also following this question. Why does the @StateObject private var jsonService: JSONService did not work even though JSONService conforms to ObservableObject. – user19037628 Jul 23 '22 at 22:54
  • 1
    @user19037628 `JSONService` doesn't conform it requires conformance. `JSONService` is a `protocol` not an object. [Here](https://docs.swift.org/swift-book/LanguageGuide/Generics.html) is some reading. – lorem ipsum Jul 23 '22 at 23:49