0

I have a function inside a model class that uses the following generic:

func loadNextPage<T: ListDiffable & JSONDecodable>(as: T.Type)

I call this function from my view controller like this:

model.loadNextPage(as: EventJSONModel.self)

However, because my view controller can be used to load data of different types, I need to specify T.Type on load of the view controller. My view controller can't be instantiated as a generic though as I'm loading it through the storyboard.

Ideally I'd like to create a variable like:

private var objectType: (ListDiffable & JSONDecodable).Type = EventJSONModel.self

Then reference it like this:

model.loadNextPage(as: objectType)

But this doesn't work... How can I do this?

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • "My view controller can't be instantiated as a generic though as I'm loading it through the storyboard.". This is possible with a protocol – J. Doe Mar 05 '19 at 11:12
  • @J.Doe What do you mean? – Tometoyou Mar 05 '19 at 11:15
  • Shouldn't you use `typealias` here? Instead of variable-with-type. Also `ListDiffable & JSONDecodable` and `T: ListDiffable & JSONDecodable` is not the same. Former is `protocol` combining two protocols, latter is some type implementing both of protocols. – user28434'mstep Mar 05 '19 at 11:34

1 Answers1

1

You are passing Protocol.Type to generic T.Type, which cannot be done directly. There are some hacks around though. Check out this thread.
Why can't I pass a Protocol.Type to a generic T.Type parameter?

Subash thapa
  • 47
  • 1
  • 4