简体   繁体   English

数组扩展通用Equatable-“无法使用…调用'=='

[英]Array extension generic Equatable - “Cannot invoke '==' with …”

I am trying to write an extension of the Swift Array, but I am getting some wierd errors as I try to compile. 我正在尝试编写Swift数组的扩展,但是在尝试编译时遇到了一些奇怪的错误。

My code: 我的代码:

extension Array
{
    func itemExists<T: Equatable>(item: T) -> Bool
    {
        for elt in self
        {
            if elt == item
            {
                return true
            }
        }
        return false
    }
}

Error: 错误:

Cannot invoke '==' with an argument list of type '(T, T)' 无法使用类型为((T,T)'的参数列表调用'=='

Why am I getting this? 我为什么得到这个? I am using the Equatable protocol? 我正在使用Equatable协议?

What I also tried was: 我还尝试过的是:

extension Array
{
    func itemExists<T: Equatable>(item: T) -> Bool
    {
        var array:[T] = self
        for elt in array
        {
            if elt == item
            {
                return true
            }
        }
        return false
    }
}

Where I got a funny error: 我收到一个有趣的错误的地方:

'T' is not identical to 'T' “ T”与“ T”不同

What am I missing? 我想念什么? I read the Apple Documentation about it but I am already using the Equatable protocol to be able to use the == operator on 'T' . 我已经阅读了Apple文档,但是我已经在使用Equatable协议来在'T'上使用==运算符。

With Swift 3.0 (and I think some of the later 2.x versions), you can solve this by referencing the associated type Element with a where clause: 使用Swift 3.0(我认为有些更高的2.x版本)可以通过使用where子句引用关联的Element类型来解决:

extension Array where Element: Equatable
{
    func itemExists(item: Element) -> Bool
    {
        for elt in self
        {
            if elt == item
            {
                return true
            }
        }
        return false
    }
}

I found my solution. 我找到了解决方案。

As MartinR alreary said, my method would only be applicable to arrays of Equatable elements, and you cannot write a method on a generic type that is more restrictive on the template. 正如MartinR alreary所说,我的方法仅适用于Equatable元素数组,并且您不能在对模板有更多限制的通用类型上编写方法。

There are two ways - writing my code as a function and not as an extension, or use this trick: 有两种方法-将我的代码作为函数而不是扩展来编写,或者使用此技巧:

extension Array
{
    func itemExists<T: Equatable>(item: T) -> Bool
    {
        return self.filter({$0 as? T == item}).count > 0
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM