Comparable. Compare Custom Objects in Swift.

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 a name “Friend”
  • Make Friend class conform to a Comparable protocol
  • Create two instances of a Friend class and compare them

Here is a short Swift code example which 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

Checkout more Swift code examples at Swift Code Examples page.


Learn iOS Development with these Video Courses


How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon


iOS 10 & Swift 3: From Beginner to Paid Professional
icon


The Complete iOS 10 Developer Course - Build 21 Apps
icon


Swift 3 - Learn to Code with Apple's New Language
icon icon


Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook