Created
January 7, 2020 01:56
-
-
Save omochi/80f8318eebf31d952e7472793c4dce78 to your computer and use it in GitHub Desktop.
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
// see also https://gist.github.com/tarunon/85bdeccf8bc8f44b7b27d4974e0a843f | |
public protocol MaybeEquatable { | |
func _isEqual(to other: Any) -> Bool | |
func __isEqual(to other: Any) -> Bool | |
} | |
extension MaybeEquatable { | |
public func __isEqual(to other: Any) -> Bool { | |
return false | |
} | |
} | |
extension MaybeEquatable where Self: Equatable { | |
public func __isEqual(to other: Any) -> Bool { | |
guard let other = other as? Self else { return false } | |
return self == other | |
} | |
} | |
extension MaybeEquatable { | |
public func _isEqual(to other: Any) -> Bool { | |
// you can use dynamic conditional dispatch here | |
__isEqual(to: other) | |
} | |
} | |
// end user interface | |
func anyIsEqual(_ a: Any, _ b: Any) -> Bool { | |
guard let a = a as? MaybeEquatable else { return false } | |
return a._isEqual(to: b) | |
} | |
// you need to mark your type | |
extension String: MaybeEquatable {} | |
print(anyIsEqual("str", "str")) // => true | |
print(anyIsEqual({}, {})) // => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment