Skip to content

Instantly share code, notes, and snippets.

@omochi
Created January 7, 2020 01:56
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 omochi/80f8318eebf31d952e7472793c4dce78 to your computer and use it in GitHub Desktop.
Save omochi/80f8318eebf31d952e7472793c4dce78 to your computer and use it in GitHub Desktop.
// 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