0

在 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”类型的操作数

4

1 回答 1

0

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

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

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

OR IfMyProtocol也可以通过structor实现enum,与条件向下转换对象进行比较。

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

这是有效的,因为===接受Optional参数。

func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool
于 2015-09-10T02:17:23.407 回答