Skip to content

Instantly share code, notes, and snippets.

@mcritz
Last active February 18, 2020 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcritz/03044ed78a4613b84364e189027cefdc to your computer and use it in GitHub Desktop.
Save mcritz/03044ed78a4613b84364e189027cefdc to your computer and use it in GitHub Desktop.
EquatableThroughMirror: compare two Types and return true if their properties and values are identical
import Foundation
/// Create a custom operator
infix operator =≈=
/// Equatable through introspection
/// Compares lhs to rhs and returns true of both sides have the same property names and values
/// - Parameters:
/// - lhs: lefthand side
/// - rhs: righthand side
func =≈= <T>(lhs: T, rhs: T) -> Bool {
let leftSideChildren = Mirror(reflecting: lhs).children
let riteSideChildren = Mirror(reflecting: rhs).children
if leftSideChildren.count != riteSideChildren.count {
return false
}
let allPropertiesAndValuesMatch = leftSideChildren.allSatisfy { leftChild in
let isContained = riteSideChildren.contains { (label, value) -> Bool in
return leftChild.label == label && String(describing: leftChild.value) == String(describing: value)
}
return isContained
}
return allPropertiesAndValuesMatch
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment