Swift 类型为 Set<Self> 的协议 属性
Swift protocol property of type Set<Self>
我正在尝试创建简单的协议:
protocol Groupable
{
var parent: Self? { get }
var children: Set<Self> { get }
}
但是 children
属性 无法编译,因为:Type 'Self' does not conform to protocol 'Hashable'
.
有什么方法可以确保 Self
成为 Hashable
吗?或任何其他解决方法,例如使用 associatedtype
?
在协议中设置约束的方式类似于指定协议一致性的方式(毕竟它们是一回事)
protocol Groupable: Hashable
{
var parent: Self? { get }
var children: Set<Self> { get }
}
您需要使用协议继承:
A protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits. The syntax for protocol inheritance is similar to the syntax for class inheritance, but with the option to list multiple inherited protocols, separated by commas.
通过从 Hashable 继承,您的 class 将需要符合此协议。
此外,在您的具体示例中,您需要将 class 设为最终版本。有关解释,请参阅
这是一个例子:
protocol Groupable: Hashable {
var parent: Self? { get }
var children: Set<Self> { get }
}
final class MyGroup: Groupable {
var parent: MyGroup?
var children = Set<MyGroup>()
init() {
}
var hashValue: Int {
return 0
}
}
func ==(lhs: MyGroup, rhs: MyGroup) -> Bool {
return true
}
let a = MyGroup()
我正在尝试创建简单的协议:
protocol Groupable
{
var parent: Self? { get }
var children: Set<Self> { get }
}
但是 children
属性 无法编译,因为:Type 'Self' does not conform to protocol 'Hashable'
.
有什么方法可以确保 Self
成为 Hashable
吗?或任何其他解决方法,例如使用 associatedtype
?
在协议中设置约束的方式类似于指定协议一致性的方式(毕竟它们是一回事)
protocol Groupable: Hashable
{
var parent: Self? { get }
var children: Set<Self> { get }
}
您需要使用协议继承:
A protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits. The syntax for protocol inheritance is similar to the syntax for class inheritance, but with the option to list multiple inherited protocols, separated by commas.
通过从 Hashable 继承,您的 class 将需要符合此协议。
此外,在您的具体示例中,您需要将 class 设为最终版本。有关解释,请参阅
这是一个例子:
protocol Groupable: Hashable {
var parent: Self? { get }
var children: Set<Self> { get }
}
final class MyGroup: Groupable {
var parent: MyGroup?
var children = Set<MyGroup>()
init() {
}
var hashValue: Int {
return 0
}
}
func ==(lhs: MyGroup, rhs: MyGroup) -> Bool {
return true
}
let a = MyGroup()