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

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon