Last active
February 18, 2020 22:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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