Swift,Equatable协议有Bug吗?

3

我正在使用Swift构建一个非常简单的结构体,其中包含一个可选值数组。这个结构体必须符合Equatable协议。以下是代码:

struct MyTable: Equatable {
    var values: [Int?] = Array(count: 64, repeatedValue: nil)
}

func == (lhs: MyTable, rhs: MyTable) -> Bool {
    return lhs.values == rhs.values
}

非常简单。我没有发现错误,但编译器报错:“'[Int?]'不可转换为'MyTable'”。是我做了什么愚蠢的事情吗?还是这是编译器的bug?谢谢!

(使用Xcode6-Beta5)


如果将“values”数组声明为[Int]而不是[Int?],则一切正常。为什么[Int?]不能正常工作? - George
2个回答

7
它不起作用的原因是,对于具有可选元素的数组,没有定义 == 运算符,只有对于非可选元素才定义了该运算符:
/// Returns true if these arrays contain the same elements.
func ==<T : Equatable>(lhs: [T], rhs: [T]) -> Bool

您可以提供自己的内容:
func ==<T : Equatable>(lhs: [T?], rhs: [T?]) -> Bool {
    if lhs.count != rhs.count {
        return false
    }

    for index in 0..<lhs.count {
        if lhs[index] != rhs[index] {
            return false
        }
    }

    return true
}

哦!我忽略了这个。奇怪它没有被定义...谢谢! - George
太棒了。谢谢伙计! - pommefrite

0
另一个有用的选项是使用SequenceType上可用的elementsEqual:isEquivalent:方法。这可以让您避免实现Equatable,但最好很少使用,因为它更冗长。
用法:
let a: [Int?] = []
let b: [Int?] = []

if a.elementsEqual(b, isEquivalent: { $0 == $1 }) {
    print("foo") // Works
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接