I want to unit-test some code that creates values with types of the form [T?] (arrays of optionals). But == is not defined for arrays of optionals:
Binary Operator '==' cannot be applied to two '[String?]' operands
So I extend Array accordingly (following this answer):
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) { $0 && ($1.0 == $1.1) }
}
}
}
But now I get:
Ambiguous reference to member '=='
In combination, the messages don't seem to make sense; how can I go from zero fitting methods/functions to more than one?
How can I extend Array for checking equality of arrays of optionals?
If you want to keep it as an extension to Array:
The
forloop here is more efficient for 2 reasons: (a) you don't have to construct a temporary array of tuples like withzipand (b) it returnsfalseas soon as a non-match is found.