Skip to content

Instantly share code, notes, and snippets.

@DandyLyons
Last active December 12, 2024 22:06
Show Gist options
  • Select an option

  • Save DandyLyons/d19c2b2444db743372fbe9f21d93c98a to your computer and use it in GitHub Desktop.

Select an option

Save DandyLyons/d19c2b2444db743372fbe9f21d93c98a to your computer and use it in GitHub Desktop.
Selective Equality Checking in Swift

Selective Equality Checking in Swift

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!

Background

To see my thought process of how and why I created this, check out my blog post: Selective Equality Checking in Swift.

Usage

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)) // false

You can try it out online in this playground on Swift Fiddle!

protocol SelectiveEquatable {
func isEqual<each V: Equatable>(to other: Self, by keyPath: repeat KeyPath<Self, each V>) -> Bool
}
extension SelectiveEquatable {
func isEqual<each V: Equatable>(to other: Self, by keyPath: repeat KeyPath<Self, each V>) -> Bool {
for kp in repeat each keyPath {
if self[keyPath: kp] != other[keyPath: kp] {
return false
}
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment