我正在尝试编写 Swift 数组的扩展,但在尝试编译时遇到一些奇怪的错误。
我的代码:
extension Array
{
func itemExists<T: Equatable>(item: T) -> Bool
{
for elt in self
{
if elt == item
{
return true
}
}
return false
}
}
错误:
Cannot invoke '==' with an argument list of type '(T, T)'
为什么我会得到这个?我正在使用 Equatable
协议(protocol)?
我还尝试过的是:
extension Array
{
func itemExists<T: Equatable>(item: T) -> Bool
{
var array:[T] = self
for elt in array
{
if elt == item
{
return true
}
}
return false
}
}
我遇到了一个有趣的错误:
'T' is not identical to 'T'
我错过了什么?我阅读了有关它的 Apple 文档,但我已经在使用 Equatable
协议(protocol),以便能够在 'T'
上使用 ==
运算符。
最佳答案
使用 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
}
}
关于ios - 数组扩展通用 Equatable - "Cannot invoke ' = =' with ...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30319700/