3

I wrote a litle swift function like this:

func compareTest(values: [[Double]]) {
    if(values == [[1.0,2.0]]) {
         // some code   
    }
}

But when I try to compile, I get an error at the comparision:

Binary operator == cannot be applied to two [[Double]] operands.

I searched in Questions around here. Most answers are that the error message is misleading and people are using the wrong type (Example Question).

Can someone help me there I wrote the types incorrect?

Community
  • 1
  • 1
Sonius
  • 1,597
  • 3
  • 14
  • 33

2 Answers2

3

In this case there is nothing misleading.

Normally the == operator is defined for Equatable items. That allows two Double values to be compared to each other, e.g. 1.0 == 1.0.

Then we have a specific == operator defined on Arrays of Equatable items:

public func ==<Element : Equatable>(lhs: [Element], rhs: [Element]) -> Bool

That means that you can compare any arrays with equatable items. However, the arrays themselves are not Equatable.

There is no such operator defined for nested arrays.

You would have to define:

public func ==<Element : Equatable>(lhs: [[Element]], rhs: [[Element]]) -> Bool {
   ...
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • 1
    Ah, I thought Arrays were Equatable when the Elements were Equatable? With a conditional protocol? Would that not make nested arrays equatable also? Or does Array not conform to the Equatable protocol at all? – Fogmeister Mar 13 '17 at 11:12
  • @Forgmeister There is just the operator, they are not Equatable. I am not sure if it's possible to make a generic to conform to a protocol if the item conforms to that protocol. – Sulthan Mar 13 '17 at 11:13
  • 2
    @Fogmeister Currently there's no conditional conformance in the language ([although there soon will be](https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md) :) ) – Hamish Mar 13 '17 at 11:14
-2

I'm not familiar with Swift but as a general rule in any language, double values should not be compared using equality operator. Instead two double values should be considered equal if their absolute arithmetic difference is small than an epsilon

var epsilon = 0.00000001;
if(fabs(v1-v2)< epsilon){ // values are considered equal
}
Luci
  • 1,278
  • 9
  • 17