Skip to content

Instantly share code, notes, and snippets.

@hallski
Created December 15, 2016 12:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hallski/5866782c60e374febb3ae658b72b370e to your computer and use it in GitHub Desktop.
Save hallski/5866782c60e374febb3ae658b72b370e to your computer and use it in GitHub Desktop.
extension Optional {
func both_then<T, U>(_ other: Optional<U>, f: (Wrapped, U) -> T) -> Optional<T> {
guard let a = self, let b = other else { return nil }
return f(a, b)
}
func neither<T>(_ other: Optional<T>) -> Bool {
return self == nil && other == nil
}
}
extension Optional where Wrapped: Equatable {
func isEqual(_ other: Optional<Wrapped>) -> Bool {
return self.neither(other) || self.both_then(other, f: ==) ?? false
}
}
let a: Int? = nil
let b: Int? = nil
let c: Int? = 2
let d: Int? = 2
let e: Int? = 3
assert(a.isEqual(b))
assert(c.isEqual(d))
assert(a.isEqual(c) == false)
assert(d.isEqual(e) == false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment