对象标识和协议

Object identity and protocols

在 Swift 中无法将对象标识与协议类型进行比较吗?我试图找到一种内置的方法来做到这一点。这是我的例子:

protocol MyProtocol {
  var propertyFoo: Int { get set }
}

class MyProtocolImpl: MyProtocol {
  var propertyFoo = 100

  func test(arg: MyProtocol) {
    if arg === self {               // error
      print("Same object")
    } else {
      print("Different object")
    }
  }
}

我收到以下错误:

二元运算符“===”不能应用于 'MyProtocol' 和 'MyProtocolImpl'

类型的操作数

要比较对象标识,操作数必须是引用类型。

所以你应该将 MyProtocol 声明为 class 协议。尝试:

protocol MyProtocol: class {
//                 ^^^^^^^
    var propertyFoo: Int { get set }
}

OR 如果MyProtocol也可以被structenum实现,与条件向下转型对象比较

if arg as? MyProtocolImpl === self {
//    ^^^^^^^^^^^^^^^^^^^

这是可行的,因为 === 接受 Optional 参数。

func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool