Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement Swift's Comparable protocol?

How do I use the Comparable protocol in Swift? In the declaration it says I'd have to implement the three operations <, <= and >=. I put all those in the class but it doesn't work. Also do I need to have all three of them? Because it should be possible to deduce all of them from a single one.

like image 990
Kametrixom Avatar asked Jun 20 '14 19:06

Kametrixom


People also ask

What is Equatable and comparable in Swift?

When should your Swift types be equatable or comparable? “Equatable” relates to being equal, and “comparable” relates to the comparison between objects. This is important, because how can we be certain that two complex objects are the same? In many circumstances, this is something that you should decide.

What is Equatable protocol in Swift?

In Swift, an Equatable is a protocol that allows two objects to be compared using the == operator. The hashValue is used to compare two instances. To use the hashValue , we first have to conform (associate) the type (struct, class, etc) to Hashable property.

What is a protocol in Swiftui?

In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types).


1 Answers

The Comparable protocol extends the Equatable protocol -> implement both of them

In Apple's Reference is an example from Apple (within the Comparable protocol reference) you can see how you should do it: Don't put the operation implementations within the class, but rather on the outside/global scope. Also you only have to implement the < operator from Comparable protocol and == from Equatable protocol.

Correct example:

class Person : Comparable {     let name : String      init(name : String) {         self.name = name     } }  func < (lhs: Person, rhs: Person) -> Bool {     return lhs.name < rhs.name }  func == (lhs: Person, rhs: Person) -> Bool {     return lhs.name == rhs.name }  let paul = Person(name: "Paul") let otherPaul = Person(name: "Paul") let ben = Person(name: "Ben")  paul > otherPaul  // false paul <= ben       // false paul == otherPaul // true 
like image 106
Kametrixom Avatar answered Sep 20 '22 06:09

Kametrixom