gpt4 book ai didi

swift - 需要扩展什么协议(protocol)以允许泛型类型的 === 运算符? (错误 : Binary operator '===' cannot be applied to two 'T' operands)

转载 作者:可可西里 更新时间:2023-11-01 00:59:45 25 4
gpt4 key购买 nike

我收到编译器错误:

Binary operator '===' cannot be applied to two 'T' operands

其中 T 是泛型类型,我只是比较 T 类型的两个项目。

所以我想我需要告诉它 === 运算符可以通过使 T 扩展协议(protocol)来在 T 上使用。如果它是 ==,我会使用 Equatable,但我看不出我应该使用什么来进行身份比较。

或者有变通办法吗?

编辑:

下面是一段说明问题的示例代码。我在这里添加了“AnyObject”,它会在实例化类时导致编译错误。如果删除“AnyObject”,则会导致“===”出错。

import Foundation

protocol Messenger : AnyObject {
func notify();
}

class PostOffice<T : AnyObject> {
var messengers : [T] = []

func addMessenger(messenger : T) {
messengers.append(messenger)
}

func deleteMessenger(messenger : T) {
for i in 0 ..< messengers.count {
if messengers[i] === messenger { // error if AnyObject not used
messengers.removeAtIndex(i)
return
}
}
}

func handleDelivery(messenger : T) {} // to be overridden

func deliver() {
for messenger in messengers {
handleDelivery(messenger)
}
}
}

let p : PostOffice<Messenger> = PostOffice<Messenger>() // error if AnyObject used

这种情况下的错误是:

Using 'Messenger' as a concrete type conforming to 'AnyObject' is not support.

最佳答案

如果你看一下 === 的定义方式:

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

public func ===<L : AnyCollectionType, R : AnyCollectionType>(lhs: L, rhs: R) -> Bool

您可以看到您需要确保 T 符合 AnyObjectAnyCollectionType。例如:

func f<T : AnyObject>(a: T, b: T) -> Bool {
return a === b
}

func f<T : AnyCollectionType>(a: T, b: T) -> Bool {
return a === b
}

关于swift - 需要扩展什么协议(protocol)以允许泛型类型的 === 运算符? (错误 : Binary operator '===' cannot be applied to two 'T' operands),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531327/

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