我如何扩展 Array 以便可以对可选数组进行相等性检查?

How can I extend Array so equality check of arrays of optionals are possible?

我想对一些代码进行单元测试,这些代码使用 [T?](可选数组)形式的类型创建值。但是 == 没有为可选数组定义:

Binary Operator '==' cannot be applied to two '[String?]' operands

所以我相应地扩展了 Array(在 之后):

extension Array {
    static func ==<T: Equatable>(lhs: [T?], rhs: [T?]) -> Bool {
        if lhs.count != rhs.count {
            return false
        }
        else {
            return zip(lhs,rhs).reduce(true) { [=11=] && (.0 == .1) }
        }
    }
}

但现在我得到:

Ambiguous reference to member '=='

综合来看,这些消息似乎没有意义;我怎样才能从零拟合 methods/functions 到多拟合?

如何扩展 Array 以检查可选数组的相等性?

如果你想保留它作为 Array 的扩展:

extension Array where Element : Equatable {
    static func ==(lhs: [Element?], rhs: [Element?]) -> Bool {
        if lhs.count != rhs.count {
            return false
        }
        else {
            for i in 0..<lhs.count {
                if lhs[i] != rhs[i] { return false }
            }
            return true
        }
    }
}

let a: [String?] = ["John", nil]
let b: [String?] = ["John", nil]
let c: [String?] = ["Jack", nil]

print(a == b) // true
print(a == c) // false

这里的 for 循环效率更高有两个原因:(a) 你不必像 zip 那样构造一个临时的元组数组,(b) 它 returns false 一旦发现不匹配项。