【问题标题】:Can we test if objects conforming to the same protocol are identical in swift without casting?我们可以在没有强制转换的情况下快速测试符合相同协议的对象是否相同?
【发布时间】:2015-11-09 09:40:33
【问题描述】:

我试图测试从工厂生成的两个对象是否相同,但编译器似乎不允许对仅符合相同协议的对象进行身份检查。然而,将两个对象都转换为 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

    }
  }

}

【问题讨论】:

    标签: swift


    【解决方案1】:

    身份运算符=== 只能应用于引用,即类的实例。 如果所有符合FooBar 协议的类型都是类,那么 您可以将其声明为“类协议”

    protocol FooBar : class { }
    

    然后

    if foo1! === foo2! { ... }
    

    按预期编译和工作,因为编译器“知道” 两个操作数都是对类实例的引用。

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 2023-03-23
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多