我有以下通用协议:
protocol Store {
associatedtype Model
func fetch(byId id : Int) -> Model
func add(model: Model) -> Bool
}
如何初始化/创建关联类型模型的新实例?例如
protocol RestStore: Store
extension RestStore {
func fetch(byId id : Int) -> Model {
let object = Model() // error here
// ...
return object
}
}
我收到以下错误:
Non-nominal type 'Self.Model' does not support explicit initialization
我还尝试约束模型类型,如下所示:
protocol RestStore: Store where Model == AnyClass
但这都行不通。我想创建一个关联类型的实例模型,有什么想法吗?
由于编译器不知道 Model 将是什么类型,因此它无法知道它将具有哪些初始值设定项,因此它无法知道Model()
代码是否有效。
您可以约束 Model,以便它必须符合包含要使用的初始值设定项的协议。然后,您应该能够创建它。