加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift associatedtype使用

发布时间:2020-12-14 06:05:42 所属栏目:百科 来源:网络整理
导读:swift中protocol不能使用T这种泛型,但是提供了associatedtype关键字来支持泛型 //protocol使用 associatedtype 来支持泛型protocol ObservebleType { associatedtype Element associatedtype Element2: Comparable func removeFirst() - Self.Element? func

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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读