swift associatedtype使用

swift中protocol不能使用<T>这种泛型,但是提供了associatedtype关键字来支持泛型

//protocol使用 associatedtype 来支持泛型
protocol ObservebleType {
    associatedtype Element
    associatedtype Element2: Comparable
    
    func removeFirst() -> Self.Element?
    func add(item: Element)
}
//实体类型
class Observeble<T: Comparable>: ObservebleType {
    // 实体类型需要实现具体类型
    typealias Element = T //方式1
    typealias Element2 = Int //方式2
    
    var ts: [T]
    init(t: T) {
        ts = [t]
    }
    
    func add(item: T) {
        ts.append(item)
    }
    
    func removeFirst() -> T? {
        guard ts.count > 0 else {
            return nil
        }
        return ts.remove(at: 0)
    }
}

let o = Observeble<String>.init(t: "哈哈")
o.add(item: "haha")
o.removeFirst()
o.removeFirst()
o.removeFirst()

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...