我试图测试从工厂生成的两个对象是否相同,但编译器似乎不允许对仅符合相同协议的对象进行身份检查.然而,将这两个对象转换为AnyObject似乎很好.反正有没有避免看似不必要的铸造?
这是一个简单的例子,演示了我所看到的内容(在swift 1.2中)
protocol FooBar {
}
class Foo: FooBar {
}
class Bar {
let foo1: FooBar?
let foo2: FooBar?
init() {
foo1 = Foo()
foo2 = Foo()
if foo1! as? AnyObject === foo2! as? AnyObject { // this is fine
}
if foo1! === foo2! { // Birnary operator '===' cannot be applied to two FooBar operands
}
}
}
Run Code Online (Sandbox Code Playgroud) swift ×1