How can I present in swiftUI a view in a switch case?
import Foundation
enum SideMenuViewModel: Int, CaseIterable, Decodable {
case Home
case Users
case TODOs
case AboutUs
var title: String {
switch self {
case .Home: return "Home"
case .Users: return "Users"
case .TODOs: return "TODOs"
case .AboutUs: return "AboutUs"
}
}
var imageName: String {
switch self {
case .Home: return "bookmark.circle"
case .Users: return "person"
case .TODOs: return "list.bullet"
case .AboutUs: return "info.circle"
}
}
}
3
Answers
You need view builder property, like
Instead of trying to return a View from an enum, inject the enum into your View and switch over the enum inside the view, then return the appropriate View from there.
A ViewModel should be independent from its view type, only the view should know about the VM, not the other way around.
I would suggest to craft an enum with associated values as follows:
So, each case has its own distinct "state" (aka model) for the respective view.
In a parent view, obtain the enum value, then simply select the given state using a switch statement. Extract the view specific state and compose the view in the body:
Example for the HomeView:
Your Model:
A root view in the scene my now subscribe to the SideMenuViewModel and pass the viewState to the ContentView.