运算符重载泛型CollectionType失败

时间:2015-08-11 21:54:00

标签: swift

我正在尝试重载-=运算符以获得与CollectionType和SequenceType上的+=重载相同(但反转)的行为。但是,我遇到了以下代码的问题:

func -=<Element, C : CollectionType where C.Generator.Element == Element>(inout lhs: [Element], rhs: C)
{
    lhs = lhs.filter { !rhs.contains($0) }
}

func -=<Element, S : SequenceType where S.Generator.Element == Element>(inout lhs: [Element], rhs: S)
{
    lhs = lhs.filter { !rhs.contains($0) }
}

导致遗憾的是,Cannot invoke 'filter' with an argument list of type '((_) -> _)'不是非常具体的错误,它本质上只是转换为“错误的论点,某处”。但考虑到函数签名中的泛型约束,我无法弄清楚为什么传递给过滤器的闭包无效?

(当然,这是Swift 2.0)

1 个答案:

答案 0 :(得分:1)

char[]要求元素为contains(),所以你必须这样做 将其添加为约束:

Equatable