Reputation: 474
I have following generic protocol:
protocol Store {
associatedtype Model
func fetch(byId id : Int) -> Model
func add(model: Model) -> Bool
}
How can I init/create a new instance of the associatedtype Model? e.g.
protocol RestStore: Store
extension RestStore {
func fetch(byId id : Int) -> Model {
let object = Model() // error here
// ...
return object
}
}
I get following error:
Non-nominal type 'Self.Model' does not support explicit initialization
I have also tried to constraint the Model type, something like this:
protocol RestStore: Store where Model == AnyClass
but this neither works. I want create an instance of the associated type Model, any ideas?
Upvotes: 1
Views: 1186
Reputation: 17060
Since the compiler doesn't know what type Model is going to be, it has no way of knowing what initializers it will have, so there's no way for it to know whether Model()
is valid code or not.
You could constrain Model so that it has to conform to a protocol containing the initializer that you want to use. Then, you should be able to create it.
Upvotes: 2