I get compiler error:
Generic parameter 'ViewModel' could not be inferred
at this point
NavigationLink(destination: TabbedView(viewModel: getModel(subSection: subSection.subSection), contentController: ContentController(), subSection: subSection.subSection)) {
Text(subSection.subSection.title)
}
my functions:
func getModel<ViewModel: ModelProtocol>(subSection: SubSection) -> ViewModel {
if(SubSection.TEXT.contains(subSection.category)){
return getLiteratureModel(subSection: subSection) as! ViewModel
}
if(SubSection.QUESTION.contains(subSection.category)){
return getTwoStepsModel(subSection: subSection) as! ViewModel
}
}
func getLiteratureModel(subSection: SubSection) -> some ModelProtocol{
let literatureModel = LiteratureModel<Any>()
literatureModel.update(subSectionId: subSection.id, category: subSection.category, lightMode: colorScheme == .light, dataSource: dataSource)
literatureModel.prepareData()
return literatureModel
}
func getTwoStepsModel(subSection: SubSection) -> some ModelProtocol{
let twoStepsModel = TwoStepsModel<Any>()
twoStepsModel.update(subSectionId: subSection.id, category: subSection.category, lightMode: colorScheme == .light, dataSource: dataSource)
twoStepsModel.prepareData()
return twoStepsModel
}
my classes
class LiteratureModel<ViewModel>: TextViewModel, ModelProtocol {...}
class TwoStepsModel<ViewModel>: TextViewModel, ModelProtocol {...}
of Protocol:
protocol ModelProtocol: ObservableObject {
associatedtype ViewModel
var htmlText: String { get } ...}
View that is called:
struct TabbedView<ViewModel>: View where ViewModel: ModelProtocol{
@ObservedObject var viewModel: ViewModel
var contentController: ContentController
var subSection: SubSection
var body: some View {
GeometryReader { geoProxy in
TabView {
if(SubSection.TEXT.contains(subSection.category)){
BaseTextView(viewModel: viewModel as! LiteratureModel<ViewModel>, contentController: contentController).padding()
.tabItem {
Text(NSLocalizedString("lesson", comment: ""))
} }
if(SubSection.QUESTION.contains(subSection.category)){
BaseTextView(viewModel: viewModel as! TwoStepsModel<ViewModel>, contentController: contentController).padding()
.tabItem {
Text(NSLocalizedString("lesson", comment: ""))
} }
...
My intention is, to reuse BaseTextView and therefore using generic type for the two Observables LiteratureModel and TwoStepsModel. I have to instantiate these classes before TabbedView gets instantiated, otherwise the Observables would be unwillingly reinstantiated.
Maybe I'm confused about Protocol, Generics, Typealias, Opaque ...