Protocol泛型

在class中泛型声明十分简单,直接类名后面➕ <T : Any>就能够了,那么Protocol中的泛型应该如何使用呢?

任务

理想中protocol中的泛型使用应该是这样的swift

protocol XProtocol<T : Any> {
    var param : [T]{get set}
    func testFun() -> T
}

但实际上Protocol是不支持这样的泛型声明的,那么咱们如何实现以上代码的功能呢?code

实现

protocol中使用泛型涉及到associatedtype关键字,这个关键字应该怎么用,具体咱们看看代码ci

protocol FxProtocol {
    associatedtype T
    
    var param : [T]{get set}
    func testFun() -> T
}

在class中,咱们定义一下T的具体类型便可get

class Test : FxProtocol{
    typealias T = String
    
    var param: [String] = []
    
    func testFun() -> String {
        return ""
    }
    
}
相关文章
相关标签/搜索