您的位置:首页 > 移动开发 > Swift

swift associatedtype使用

2017-09-25 00:00 351 查看
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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  associatedtype