This gist vends a new protocol called SelectiveEquatable which contains a single method, isEqual(to:by:). This method allows you to check the equality
of two values by selectively picking which properties you would like to compare.
SelectiveEquatable is also available as a Swift Package!
To see my thought process of how and why I created this, check out my blog post: Selective Equality Checking in Swift.
class MyClass: SelectiveEquatable {
init(int: Int, string: String) {
self.int = int
self.string = string
}
var int: Int
var string: String
}
let myClass1 = MyClass(int: 4, string: "string")
let myClass2 = MyClass(int: 3, string: "string")
print(myClass1.isEqual(to: myClass2, by: \.string)) // true
print(myClass1.isEqual(to: myClass2, by: \.string, \.int)) // falseYou can try it out online in this playground on Swift Fiddle!