0

I have an array of type tuple (Date, MyOwnClass) and try to find the index of a specific tuple that equals to my target tuple from the tuple array. XCode is giving me error saying "Binary operator == can not..." when I tried to use ".indexOf({ $0 == targetTuple })"

Thanks in advance!

Nick Chang
  • 1
  • 1
  • 4

1 Answers1

0

Tuples automatically conform to Equatable protocol if all its elements also conform to it, so you just need to make sure that your class implements Equatable protocol:

class MyClass {
  var name : String
  init(_ _name : String) {
    name = _name
  }
}

extension MyClass: Equatable {
  public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {
    return lhs.name == rhs.name
  }
}

let ar : [(Int, MyClass)] = [
  (1, MyClass("A")),
  (2, MyClass("B")),
  (1, MyClass("A"))
]

if let ix = ar.index(where:{$0 == (1, MyClass("A"))}) {
  print(ix)
} else {
  print("not found")
}

// 0 is printed
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • Minor correction: There are `==` operators for tuples of equatable elements, but the tuples do not conform to the `Equatable` protocol. – Martin R Oct 16 '17 at 18:57
  • Thank you very much for your answer. Since protocol, Equatable, is a new thing to me, I have questions about when to use it and why I need it for my tuple. Thanks!! – Nick Chang Oct 22 '17 at 16:21