Snips
Snips

Reputation: 6773

Passing different instances of same Model to same SwiftUI View struct

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 SceneDelegate,

    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: SantaList
    @EnvironmentObject var niceModel: SantaList

    var body: some View {
        TabView(selection: $selection){
            SantaListView().environmentObject(naughtyModel)
                .font(.title)
                .tabItem {
                    VStack {
                        Text(naughtyModel.title)
                    }
                }
                .tag(0)
            SantaListView().environmentObject(niceModel)
                .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 goes awry...

struct SantaListView: View {

    @EnvironmentObject var santaListModel: SantaList // <<< the problem: naughty or nice?

    var body: some View {
        NavigationView() {
            VStack {
            }
           .navigationBarTitle(Text(santaListModel.title))
        }
    }
}

In SantaList class implementation, how do I refer to the specific @EnvironmentVariable, such that santaListModel above refers to the specific instance naughtyModel or niceModel?

Thanks in advance.

Upvotes: 1

Views: 889

Answers (1)

pd95
pd95

Reputation: 2642

I recommend you to simply create two subclasses for the model:

class NaughtyList: SantaListModel {
  init() {
    super.init(title: "Naughty")
  }
}

class NiceList: SantaListModel {
  init() {
    super.init(title: "Nice")
  }
}

By doing this, both lists can be stored in the environment without clashing. The only thing SwiftUI has to distinguish environment objects is by class. Therefore it is important to have separate classes.

Upvotes: 1

Related Questions