Protocol泛型

在class中泛型声明十分简单,直接类名后面➕ 就可以了,那么Protocol中的泛型应该如何使用呢?

任务

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

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

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

实现

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

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

在class中,我们定义一下T的具体类型即可

class Test : FxProtocol{
    typealias T = String
    
    var param: [String] = []
    
    func testFun() -> String {
        return ""
    }
    
}

你可能感兴趣的:(protocol,ios,swift)