Skip to content

Instantly share code, notes, and snippets.

@josipbernat
Created November 4, 2020 11:49
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 josipbernat/a7f6e409d4d3182d3875acdd017a39e4 to your computer and use it in GitHub Desktop.
Save josipbernat/a7f6e409d4d3182d3875acdd017a39e4 to your computer and use it in GitHub Desktop.
Compare enum with associated value by ignoring their associated values
// Thanks to following StackOverflow answer:
// https://stackoverflow.com/questions/47597489/compare-swift-enum-types-ignoring-associated-values-generic-implementation
protocol ComparableCaseEnum {
func isSameCase(as other: Self) -> Bool
}
extension ComparableCaseEnum {
func isSameCase(as other: Self) -> Bool {
let mirrorSelf = Mirror(reflecting: self)
let mirrorOther = Mirror(reflecting: other)
if let caseSelf = mirrorSelf.children.first?.label, let caseOther = mirrorOther.children.first?.label {
return (caseSelf == caseOther) //Avoid nil comparation, because (nil == nil) returns true
} else { return false}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment