Can we test if objects conforming to the same protocol are identical in swift without casting? -
i trying test if 2 objects generated factory identical, compiler not seem allow identity checking of objects merely conform same protocol. casting both objects anyobject seems fine however. there anyway avoid seems unnecessary casting?
here simple example demonstrates seeing (in 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 { // fine } if foo1! === foo2! { // birnary operator '===' cannot applied 2 foobar operands } } }
the identity operator ===
can applied references, i.e. instances of classes. if types conforming foobar
protocol classes can declare "class protocol"
protocol foobar : class { }
then
if foo1! === foo2! { ... }
compiles , works expected, because compiler "knows" both operands references class instance.
Comments
Post a Comment