Comparable protocol. Compare custom objects. 

Often we create custom classes like Person or Address and then need to compare if the two instances of this class or Objects are equal. With this Swift code example, I would like to share with you how to compare two objects of a custom class you create by making a custom class conform to a Comparable protocol.

  • Create a custom Swift class with the name “Friend”
  • Make Friend class conform to a Comparable protocol
  • Create two instances of a Friend class and compare them

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Here is a short Swift code example that demonstrates how to implement a custom class in Swift and make it conform to a Comparable protocol.

Make Custom Class Conform to a Comparable Protocol Example in Swift

  
 import Foundation

class Friend : Comparable {
    let name : String
    let age : Int
    
    init(name : String, age: Int) {
        self.name = name
        self.age = age
    }
}

func < (lhs: Friend, rhs: Friend) -> Bool {
    return lhs.age < rhs.age } func > (lhs: Friend, rhs: Friend) -> Bool {
    return lhs.age > rhs.age
}

func == (lhs: Friend, rhs: Friend) -> Bool {
    var returnValue = false
    if (lhs.name == rhs.name) && (lhs.age == rhs.age)
    {
        returnValue = true
    }
    return returnValue
}

Compare Two Custom Objects that Implement Comparable Protocol

  

        let friend1 = Friend(name: "Sergey", age: 35)
        let friend2 = Friend(name: "Sergey", age: 30)
        
        print("\Compare Friend object. Same person? (friend1 == friend2)")  // false

Before you go, checkout other short Swift code examples on Swift Code Examples page.

Leave a Reply

Your email address will not be published.