【问题标题】:Swift initialization of associatedtype inside protocol extension协议扩展内关联类型的 Swift 初始化
【发布时间】:2017-08-12 13:36:42
【问题描述】:

我有以下通用协议:

protocol Store {
    associatedtype Model 

    func fetch(byId id : Int) -> Model
    func add(model: Model) -> Bool
}

如何初始化/创建关联类型 Model 的新实例?例如

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

我也尝试过约束 Model 类型,如下所示:

protocol RestStore: Store where Model == AnyClass

但这都不起作用。我想创建一个关联类型 Model 的实例,有什么想法吗?

【问题讨论】:

    标签: swift generics swift3 swift-protocols


    【解决方案1】:

    由于编译器不知道 Model 将是什么类型,它无法知道它将具有哪些初始化程序,因此它无法知道 Model() 是否是有效代码。

    您可以约束模型,使其必须符合包含您要使用的初始化程序的协议。然后,您应该能够创建它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2016-07-06
      • 1970-01-01
      相关资源
      最近更新 更多