Created
August 10, 2021 09:33
-
-
Save drewmccormack/a3928f56ea4e3827e2de3de0d1912a37 to your computer and use it in GitHub Desktop.
Introduces a Set type that stores enums, including those with associated types, and uniques on the label rather than the value.
This file contains 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
struct Label: Hashable { | |
var label: String | |
} | |
protocol LabelUniquing { | |
var label: Label { get } | |
} | |
extension LabelUniquing { | |
var label: Label { | |
let label = Mirror(reflecting: self).children.first?.label ?? String(describing: self) | |
return Label(label: label) | |
} | |
} | |
struct LabelUniqueSet<T: LabelUniquing> { | |
private var valuesByLabel: [Label:T] = [:] | |
mutating func insert(value: T) { valuesByLabel[value.label] = value } | |
mutating func remove(label: Label) { valuesByLabel[label] = nil } | |
func value(forLabel label: Label) -> T? { valuesByLabel[label] } | |
} | |
// Tests | |
enum Test: LabelUniquing { | |
case a | |
case b(value: String) | |
} | |
var set = LabelUniqueSet<Test>() | |
set.insert(value: .a) | |
set.insert(value: .b(value: "1")) | |
set.insert(value: .b(value: "2")) | |
let valueForB = set.value(forLabel: Label(label: "b"))! | |
print("This should be 2 ... \(valueForB)") | |
let valueForA = set.value(forLabel: Label(label: "a"))! | |
print("Value for a ... \(valueForA)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment