Skip to content

Instantly share code, notes, and snippets.

@dabrahams
Created December 8, 2016 02:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dabrahams/81f0cb0d181198c1ac43b281b7314d28 to your computer and use it in GitHub Desktop.
Save dabrahams/81f0cb0d181198c1ac43b281b7314d28 to your computer and use it in GitHub Desktop.
Faux Equatable and Comparable Existentials
class AnyEquatableBase {
func isEqual(to other: AnyEquatableBase) -> Bool {
fatalError("overrideMe")
}
}
class AnyEquatableBox<T: Equatable> : AnyEquatableBase {
let value: T
init(_ value: T) { self.value = value }
override func isEqual(to other: AnyEquatableBase) -> Bool {
if let otherSelf = other as? AnyEquatableBox<T> {
return self.value == otherSelf.value
}
return false
}
}
struct AnyEquatable : Equatable {
let box: AnyEquatableBase
init<T: Equatable>(_ x: T) {
box = AnyEquatableBox(x)
}
static func == (l: AnyEquatable, r: AnyEquatable) -> Bool {
return l.box.isEqual(to: r.box)
}
}
class AnyComparableBase : AnyEquatableBase {
func isLess(than other: AnyComparableBase) -> Bool {
fatalError("overrideMe")
}
}
class AnyComparableBox<T: Comparable> : AnyComparableBase {
let value: T
init(_ value: T) { self.value = value }
override func isEqual(to other: AnyEquatableBase) -> Bool {
if let otherSelf = other as? AnyComparableBox<T> {
return self.value == otherSelf.value
}
return false
}
override func isLess(than other: AnyComparableBase) -> Bool {
guard let otherSelf = other as? AnyComparableBox<T> else {
fatalError("mixed type ordering comparison not supported")
}
return self.value < otherSelf.value
}
}
struct AnyComparable : Comparable {
let box: AnyComparableBase
init<T: Comparable>(_ x: T) {
box = AnyComparableBox(x)
}
static func == (l: AnyComparable, r: AnyComparable) -> Bool {
return l.box.isEqual(to: r.box)
}
static func < (l: AnyComparable, r: AnyComparable) -> Bool {
return l.box.isLess(than: r.box)
}
}
@nubbel
Copy link

nubbel commented Jul 27, 2017

Thanks, exactly what I needed!

@michaelcordero
Copy link

Does this type have a swift evolution proposal number? I want to know why this isn't included in stdlib. Thanks.

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