Created
April 6, 2020 08:17
-
-
Save nalexn/1175f9d4b7ad6f7b3d87c76df04e3c36 to your computer and use it in GitHub Desktop.
Equatable without the need to implement == func
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
protocol BinaryEquatable: Equatable { } | |
extension BinaryEquatable { | |
static func == (lhs: Self, rhs: Self) -> Bool { | |
withUnsafeBytes(of: lhs) { lhsBytes -> Bool in | |
withUnsafeBytes(of: rhs) { rhsBytes -> Bool in | |
lhsBytes.elementsEqual(rhsBytes) | |
} | |
} | |
} | |
} | |
// Example: | |
enum TestEnum { | |
case option1 | |
case option2(String) | |
case option3(String, completion: (() -> Void)?) | |
} | |
extension TestEnum: BinaryEquatable { } | |
TestEnum.option1 == TestEnum.option1 // true | |
TestEnum.option1 == TestEnum.option2("abc") // false | |
TestEnum.option2("abc") == TestEnum.option2("abc") // true | |
TestEnum.option2("abc") == TestEnum.option2("xyz") // false | |
TestEnum.option2("abc") == TestEnum.option3("abc", completion: { }) // false | |
TestEnum.option3("abc", completion: nil) == TestEnum.option3("abc", completion: nil) // true | |
TestEnum.option3("abc", completion: { }) == TestEnum.option3("abc", completion: nil) // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment