Skip to content

Instantly share code, notes, and snippets.

@josipbernat
Last active November 4, 2020 15:45
Show Gist options
  • Save josipbernat/ddd6a3bb21c34007afb611127de2d390 to your computer and use it in GitHub Desktop.
Save josipbernat/ddd6a3bb21c34007afb611127de2d390 to your computer and use it in GitHub Desktop.
Enum with associated values that can be updated
enum PersonInfo {
// CustomDebugStringConvertible is here for easier printing to console.
// Feel free to remove it if you don't need it.
class EnumValue<T>: CustomDebugStringConvertible {
var value: T
init(_ value: T) {
self.value = value
}
var debugDescription: String {
"\(value)"
}
}
// Instead of using String or Bool or any other type directly, use EnumValue wrapper
case firstName(EnumValue<String>)
case lastName(EnumValue<String>)
case isAdult(EnumValue<Bool>)
// For some reason this won't work. If anybody knows why
// guard let value = associatedValue.value as? EnumValue<V> fails
// please comment below!
// func updateAssociatedValue<V>(_ updateValue: V) {
// let mirror = Mirror(reflecting: self)
// for associatedValue in mirror.children {
// guard let value = associatedValue.value as? EnumValue<V> else {
// continue
// }
// value.value = updateValue
// }
// }
// Until then for each type write own update function
func updateAssociatedValue(_ updateValue: String) {
let mirror = Mirror(reflecting: self)
for associatedValue in mirror.children {
guard let value = associatedValue.value as? EnumValue<String> else {
continue
}
value.value = updateValue
}
}
func updateAssociatedValue(_ updateValue: Bool) {
let mirror = Mirror(reflecting: self)
for associatedValue in mirror.children {
guard let value = associatedValue.value as? EnumValue<Bool> else {
continue
}
value.value = updateValue
}
}
}
var array: [PersonInfo] = [
.firstName(PersonInfo.EnumValue("John")),
.lastName(PersonInfo.EnumValue("Doe")),
.isAdult(PersonInfo.EnumValue(false))
]
print(array)
array.first?.updateAssociatedValue("Mike")
print(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment