Thursday, August 9, 2018

Swift Comparable Protocol

Before reading this post, I would suggest to go through my post on Equatable protocol

Because, Comparable protocol extends from Equatable Protocol.

Equatable helps in comparing custom class objects and finding them in a collection.

Comparable protocol helps in comparing(< , > , <=, >=) and sorting of custom class objects.

<= and >= uses Equatble stuff as Comparable protocol extends from to Equatable protocol.

Most of the native classes confirm to comparable protocol which gives direct comparison access.

 let fruit1 = "banana"
 let fruit2 = "grapes"
      if fruit1 < fruit2  {
      else {

Most of the native classes confirm to comparable protocol which gives direct sort() method for collection.

 var fruits = ["banana", "apple", "grapes"]


 print(fruits)  //["apple", "banana", "grapes"]

Here we don’t need to write any logic.

Where as for custom classes, We need to explicitly write the sort logic by using sort(by:) method.

  struct Address: Equatable {
    let city: String
    let state: String
    let country: String

  var addresses = [

  Address(city: "Amsterdam", state: "New York", country: "America"),

  Address(city: "Belmont", state: "California", country: "America"),

  Address(city: "Hartford", state: "Connecticut", country: "America")]
 addresses.sort(by: { $0.state < $1.state })

Instead of this, Address struct can confirm to Comparable protocol and we can have ability to directly compare(< , > , <=, >=).

For Equatable, we don’t need to write boiler plate code from Swift 4.1 onwards, whereas for Comparable, we need to write.

 struct Address: Comparable {
      let city: String
      let state: String
      let country: String
      static func < (lhs: Address, rhs: Address) -> Bool {
          return <

I am comparing city name for sorting here.

Now, we can directly compare our Address custom objects with comparison operators(< , > , <=, >=).

    let currentAddress = Address(city: "Amsterdam", state: 
            "New York", country: "America")

    let selectedAddress = Address(city: "Hartford", state: 
            "Connecticut", country: "America")
        if currentAddress < selectedAddress {
            print("Show current address first")
        else {
            print("Show selectedAddress address first")

As we are mentioned the logic for Comparison, Our Address collection will have direct sort() method now.


  var addresses = [

  Address(city: "Amsterdam", state: "New York", country:      

  Address(city: "Belmont", state: "California", country: 
  Address(city: "Hartford", state: "Connecticut", country:     

That’s how we can make use of Comparable protocol and have comparison quite easy like native objects.

Hope this post is useful. Feel free to comment in case of any queries.