Is it possible to overload equivalence (==) operator for a custom class inside that custom class. However I know that it is possible to have this operator overloaded outside class scope. Appreciate any sample code. Thanks in advance.
Asked
Active
Viewed 1.2k times
18
-
see [this tutorial](http://www.raywenderlich.com/80818/operator-overloading-in-swift-tutorial) – Huy Nghia Mar 04 '15 at 06:51
-
This might be interesting in this context: http://stackoverflow.com/questions/28793218/swift-overriding-in-subclass-results-invocation-of-in-superclass-only. – Martin R Mar 04 '15 at 06:55
2 Answers
36
Add global functions. For example:
class CustomClass {
var id = "my id"
}
func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
return lhs == rhs
}
func !=(lhs: CustomClass, rhs: CustomClass) -> Bool {
return !(lhs == rhs)
}
To conform Equatable protocol in Swift 2
class CustomClass: Equatable {
var id = "my id"
}
func ==(left: CustomClass, right: CustomClass) -> Bool {
return left.id == right.id
}
To conform Equatable protocol in Swift 3
class CustomClass {
var id = "my id"
}
extension CustomClass: Equatable {
static func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
return lhs.id == rhs.id
}
}

Yoichi Tagaya
- 4,547
- 2
- 27
- 38
-
1For anyone else reading this WAY too fast (like I did), note that those func declarations are OUTSIDE of the class (hence, "global"). – ghostatron Sep 14 '16 at 22:20
-
4note that the above operators won't get fired if one of the operands is an optional. also, if both the operator's parameters are optionals, and both the operands are non-optionals, it won't get fired. make both the operator's parameters implicitly unwrapped optionals to ensure it will always be fired for your custom class; but ensure nil cases are handled, otherwise your program may crash – shoe Feb 13 '17 at 00:33