Context
考虑Swift 5.9中的这个协议和类:
protocol SpinnerHosting: AnyObject
{
var spinnerItem: SpinnerItem { get }
}
final class MyViewController: NSViewController
{
var activeChild: (NSViewController & SpinnerHosting)? = nil
func pushChild(_ incomingChild: (NSViewController & SpinnerHosting))
{
// #1
if incomingChild != activeChild {
...
}
// #2
if incomingChild != activeChild! {
...
}
}
}
Problem
在第1点,SWIFT抛出以下错误:
Type 'any NSViewController & SpinnerHosting' cannot conform to 'Equatable'
在第2点(忽略不安全的展开),它抛出以下一个:
Binary operator '!=' cannot be applied to two 'any NSViewController & SpinnerHosting' operands
Question:
我明白为什么协议不是Equatable
.但我不明白为什么编译器认为这不是.在这里,SpinnerHosting
被限制为AnyObject
,这意味着引用类型,因此指针相等.但如果我将议定书限制在NSViewController
本身,同样的错误仍然存在,这让我感到惊讶,因为NSViewController
是可以等同的.
我只是想说:"任何NSViewController
要占用activeChild
的东西都必须有spinnerItem
的属性."(我意识到我可以用子类来做到这一点;这不是我的问题.)
我刚刚在几个Apple源代码示例中看到了这种模式:var foo: ([Class] & [Protocol])
,我看不出有什么好的理由不能是Equatable
.