【问题标题】:Is there any way to use the generic protocol as a data type in a function?有没有办法将泛型协议用作函数中的数据类型?
【发布时间】:2019-04-09 05:45:45
【问题描述】:

有没有办法在函数中使用泛型协议作为数据类型?

public protocol ICRUDOperation {

    associatedtype T

    func insert(data:T)
    func update(data:T)
    func get(data:T) -> [T]
    func GetList(data: BaseModel) -> Array<T>
    func GetPage(data: BaseModel) -> Array<T>
    func Delete(data: T)
}

在下面的函数中,我得到了错误

func Delegate1<W: ICRUDOperation>(sqlite: W, service: W, data: T) {
    sqlite.insert(data: data)
}

错误:无法转换类型“T”的值(泛型的泛型参数 类'Decision')到预期的参数类型'W.T'(关联类型 协议“ICRUDOOperation”)

【问题讨论】:

    标签: swift types interface protocols


    【解决方案1】:

    如错误所述,T 是一个泛型参数,其类未在函数声明中定义,因为 TICRUDOperation 相关联,因此您应该将委托用作:

    func Delegate1<W: ICRUDOperation>(sqlite: W, service: W, data: W.T) {
        sqlite.insert(data: data)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多