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
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() } } }) } }