In SwiftUI I would like to declare an @ObservedObject var with a type defined in a protocol...

See sample code below...

Basically it's a galleryView with a dataSource that can add/remove items dynamically. It works as expected when GalleryView's dataSource variable has a type (that conforms to ObservableObject)
However when I change dataSource's type to be a protocol, I can't seem to get my code to compile.
Any guidance on how to use a protocol in GalleryView, and continue to keep the UI updating when the model object's item list changes?

thanks!
Mike


Code Block
protocol GalleryDataSource: ObservableObject {
    var itemCount: Int { get }
    func item(for index: Int) -> String
}
class GalleryModel: ObservableObject {
    static let test1: GalleryModel = GalleryModel(items: ["A","B","C"])
    @Published var items: [String]
    init(items: [String]) {
        self.items = items
    }
}
extension GalleryModel: GalleryDataSource {
    var itemCount: Int {
        return items.count
    }
    func item(for index: Int) -> String {
        return items[index]
    }
}
struct ContentView: View {
    var model: GalleryModel = GalleryModel.test1
    var body: some View {
        VStack {
            GalleryView(dataSource: model)
            Button("Add Item") {
                model.items.append("\(model.items.count)")
            }
        }
    }
}
struct GalleryView: View {
    @ObservedObject var dataSource: GalleryModel //GalleryDataSource
    var body: some View {
        ScrollView(.horizontal, content: {
            HStack {
                ForEach(0..<self.dataSource.itemCount, id:\.self) { index in
                    Text(dataSource.item(for: index))
                        .padding()
                }
            }
        })
    }
}

To declare an @ObservedObject var, you need a type conforming to ObservableObject.
The protocol GalleryDataSource does inherit ObservableObject, but does not conform to ObservableObject.

Currently, there is no way provided to make protocols to conform some other protocol in Swift.
Better find another way.

One possible alternative would be using generics:
Code Block
struct GalleryView<DataSource: GalleryDataSource>: View {
@ObservedObject var dataSource: DataSource
var body: some View {
ScrollView(.horizontal, content: {
HStack {
ForEach(0..<self.dataSource.itemCount, id:\.self) { index in
Text(dataSource.item(for: index))
.padding()
}
}
})
}
}


In SwiftUI I would like to declare an @ObservedObject var with a type defined in a protocol...
 
 
Q