Created
December 8, 2016 02:49
-
-
Save dabrahams/81f0cb0d181198c1ac43b281b7314d28 to your computer and use it in GitHub Desktop.
Faux Equatable and Comparable Existentials
This file contains hidden or 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
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) | |
} | |
} |
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
Thanks, exactly what I needed!