gpt4 book ai didi

swift - 对象标识和协议(protocol)

转载 作者:行者123 更新时间:2023-11-30 14:05:25 25 4
gpt4 key购买 nike

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

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)。尝试:

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

或者如果MyProtocol也可以通过structenum实现,则与条件向下转型对象进行比较。

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

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

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

关于swift - 对象标识和协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32490973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com