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.
[raw_html_snippet id=”cookbookpagecoursesheader”]
Unit Testing Swift Mobile App
Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.