简体   繁体   中英

Swift initialization of associatedtype inside protocol extension

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 ? eg

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM