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

标签 swift generics

我收到编译器错误:

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/

相关文章:

c# - 使用泛型重构重复方法

java - java泛型中的通配符

java - java泛型中奇怪的类型错误

ios - 多次暂停和恢复 CAEmitterLayer

ios - UIButton 中的 UIImage 用矢量图像像素化

ios - 如何防止内容滚动到 UITableView 页脚后面

c# - 在 C# 中应该如何测试变量是否为值类型?

ios - 无法使 UIButton 的图层蒙版起作用

swift - 如何更改应用程序色调颜色(新的 SwiftUI 生命周期应用程序)?

c - C 中链表的通用排序