I'm working on a SwiftUI project, and I've run into a couple of issues I can't seem to solve. Here's a brief overview of my code:
protocol FlowViewModel: ObservableObject {
var myFakeData: Int { get }
var shouldNavigate: Bool { get set }
func getNextViewModel() -> FlowViewModel
}
final class Step2VM: FlowViewModel {
@Published var shouldNavigate: Bool = false
var myFakeData: Int {
return 1
}
func getNextViewModel() -> FlowViewModel {
return Step3VM()
}
}
final class Step1VM: FlowViewModel {
@Published var shouldNavigate: Bool = false
var myFakeData: Int {
return 0
}
func getNextViewModel() -> FlowViewModel {
return Step2VM()
}
}
struct MainView<ViewModel>: View where ViewModel: FlowViewModel {
@ObservedObject var viewModel: ViewModel
var body: some View {
NavigationView {
StepView(viewModel: viewModel)
}
}
}
struct StepView<ViewModel>: View where ViewModel: FlowViewModel {
@ObservedObject var viewModel: ViewModel
var body: some View {
VStack {
NavigationLink(
destination: StepView(viewModel: viewModel.getNextViewModel()),
isActive: $viewModel.shouldNavigate,
label: { EmptyView() }
)
Text("\(viewModel.myFakeData)")
}
}
}
I'm having these errors:
Inside my protocol:
Use of protocol 'FlowViewModel' as a type must be written 'any FlowViewModel'
As you can see I am attempting to reuse StepView
for all the views and just passing in a new view model each time to populate the current data.
Is there a better approach to this?