I am confused by what I believe must be a very common architecture / implementation problem, but I can't find discussion of it. I've posted about this on StackOverflow but haven't had a satisfactory answer, so please excuse me for I'm trying here.
I have a Tab-based app, implemented in Swift, and using SwiftUI.
For 2 of the tabs, I want to show Lists based on the same SwiftUI struct, displaying different instances of the same class.
In the AppDelegate,
let naughtyModel = SantaListModel(title: "Naughty")
let niceModel = SantaListModel(title: "Nice")
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
.environmentObject(naughtyModel)
.environmentObject(niceModel)
...
Then,
struct ContentView: View {
@State private var selection = 0
@EnvironmentObject var naughtyModel: SantaListModel
@EnvironmentObject var niceModel: SantaListModel
var body: some View {
TabView(selection: $selection){
SantaListView().environmentObject(naughtyModel) // Pass down naughty list of type SantaListModel
.font(.title)
.tabItem {
VStack {
Text(naughtyModel.title)
}
}
.tag(0)
SantaListView().environmentObject(niceModel) // Pass down nice list of type SantaListModel
.font(.title)
.tabItem {
VStack {
Text(niceModel.title)
}
}
.tag(1)
}
}
}
All apparently good so far, but when I implement SantaListView, a shared struct implementation to display the different instances, the plan seems to go awry at the code level...
struct SantaListView: View {
@EnvironmentObject var santaListModel: SantaListModel // <<< This apparently matches the Env Object by type?
var body: some View {
NavigationView() {
VStack {
}
.navigationBarTitle(Text(santaListModel.title))
}
}
}
HOWEVER! This code arrangement works (I have 2 apps that work this way), and the runtime apparently matches whichever instance of the SantaListModel that is passed on by type (I had assumed the envObj passed in would need to have the same name when received, apparently not!)
I'm worried this works based on some fluke, and is not a supported mechanism.
I'm also confused why this arrangement isn't discussed commonly on the web - is there an alternative architecture trick I'm missing?
I've used naughty / nice lists as example here - but another example could be a music streaming app, where the view is presenting a music playlist - each playlist would have a model instance, and you want to display different playlists on different tabs - maybe different tabs for different moods? It seems to me to be entirely legitimate to have multiple instances of a model displayed in different places in an app using the same View code.
In SantaList class implementation, is this a legitimate way to pass the different instances of SantaListModel, naughtyModel or niceModel?
Thanks in advance.