Skip to content

Instantly share code, notes, and snippets.

@tarunon
Last active January 7, 2020 04:59
Show Gist options
  • Save tarunon/85bdeccf8bc8f44b7b27d4974e0a843f to your computer and use it in GitHub Desktop.
Save tarunon/85bdeccf8bc8f44b7b27d4974e0a843f to your computer and use it in GitHub Desktop.
public typealias PartialApplySelfToIsEqual = (Any?) -> Bool
public protocol MaybeEquatable {
func partialApplySelftoIsEqual() -> PartialApplySelfToIsEqual
}
extension MaybeEquatable {
public func partialApplySelftoIsEqual() -> PartialApplySelfToIsEqual {
{ _ in false }
}
}
extension MaybeEquatable where Self: Equatable {
public func partialApplySelftoIsEqual() -> PartialApplySelfToIsEqual {
{ self == $0 as? Self }
}
}
extension MaybeEquatable {
public func isEqual(to other: Any?) -> Bool {
self.partialApplySelftoIsEqual()(other)
}
}
// end user interface
public 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
@tarunon
Copy link
Author

tarunon commented Jan 7, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment