Ronnie
Ronnie

Reputation: 362

Generic struct from defined protocol

I know this may sound basic to a lot of people, but my brain today is working at 2 cylinders and I cannot figure this out...

I had this view working perfectly.

struct MyView: View {

  @ObservedObject private var myModel:MyModel
  
  init(myModel:MyModel) {
    self.myModel = myModel
  }

Now I have a second kind of model. I need to modify MyView to be generic.

So I have started by creating a protocol because the variables and function calls of both models will be the same and assigned these protocols to both models.

Now I need to modify the view to something like

struct MyView: View {

  @ObservedObject private var myModel:Any
  
  init(myModel:Any) {
    self.myModel = myModel
  }

But I am sure it is not the way to do that.

or something like

struct MyView<T>: View {

  @ObservedObject private var myModel:T
  
  init(myModel:T) {
    self.myModel = myModel
  }

but I cannot figure out the exact syntax.

thanks

Upvotes: 0

Views: 45

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

You're just missing the requirement that T be an ObservableObject:

struct MyView<T: ObservableObject>: View { ... }

Upvotes: 1

Related Questions