Tometoyou
Tometoyou

Reputation: 8376

How to specify generic type as variable?

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?

Upvotes: 0

Views: 105

Answers (1)

Subash thapa
Subash thapa

Reputation: 57

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?

Upvotes: 1

Related Questions