协议作为 Swift 中的哈希表(Set)的泛型类型, 一直都是很困惑的一个问题, 这里找到了两种方式来设置协议类型作为 Set 的泛型参数…
很早之前就想探究这个问题了, 实际上看到解决方法有两种.
-
第一种是使用
AnyHashable作为 Set 的泛型参数, 然后往里面添加Hashable类型:swiftvar vcSet: Set<AnyHashable> = [] let p1 = People(name: "er", age: 1, isAlive: true) let d1 = Dog(color: "green", length: 22.3, isAlive: true) print(vcSet.insert(p1)) print(vcSet.insert(d1)) protocol Animal: Hashable { var isAlive: Bool { get } } struct People: Animal { var name: String var age: Int var isAlive: Bool } struct Dog: Animal { var color: String var length: Double var isAlive: Bool } -
另外一种是使用泛型包装类来建立 Set:
swiftprotocol testProtocol: Hashable { // 协议内容 } class test<Elem: testProtocol> { var s : Set<Elem>? // ... }