假设我有一个协议Item,和一个符合它的结构ConcreteItem。
protocol Item {
var name: String { get }
}
struct ConcreteItem: Item {
let name: String
}在某种程度上,我希望有两组ConcreteItem。
let set1 = Set([ConcreteItem(name: "item1")])
let set2 = Set([ConcreteItem(name: "item2"), ConcreteItem(name: "item1")])我希望返回名为"item1"的项目。
我可以使ConcreteItem符合Hashable,并且Set代码也能工作。然而,让我们说,我也有以下几点:
struct AnotherConcreteItem: Item {
let name: String
}我希望AnotherConcreteItem也与Hashable保持一致,因为它与Item是一致的。
然而,当我试图实现这个想法时:
extension Item: Hashable {
var hashValue: Int {
return name.characters.count
}
}我得到以下错误:Extension of protocol 'Item' cannot have an inheritance clause。
发布于 2017-07-30 01:10:34
协议“项”的扩展不能有继承子句
这里的项目是协议,因此符合Hashable协议将无法工作。有关更多详细信息,请参阅这里
发布于 2017-07-30 01:18:15
你试图做的是一些协议是可能的,但不是全部。如果您试图遵循的协议没有任何关联类型或Self,则这是可能的。
示例:
protocol A {
func foo()
}
protocol Item: A {
var name: String { get }
}
struct ConcreteItem: Item {
let name: String
}
extension Item {
func foo() {
}
}所有符合Item的东西也将符合A。
但是,Hashable有Self约束。要符合Hashable,还必须遵守Equatable。为了符合Equatable,==的实现必须在一个具体的类中,而不是在另一个协议中,因为Equatable不能用作参数类型。你能做的最多就是这样的事情:
protocol Item: Hashable {
var name: String { get }
}
struct ConcreteItem: Item {
let name: String
// you need to implement == in every concrete class
static func ==(lhs: ConcreteItem, rhs: ConcreteItem) -> Bool {
return ...
}
}
extension Item {
var hashValue: Int {
return name.characters.count
}
}https://stackoverflow.com/questions/45395312
复制相似问题