Skip to content

Instantly share code, notes, and snippets.

@isoiphone
Last active August 17, 2018 03:17
Show Gist options
  • Save isoiphone/8132f76045253bf40b6ba9a62444b9d6 to your computer and use it in GitHub Desktop.
Save isoiphone/8132f76045253bf40b6ba9a62444b9d6 to your computer and use it in GitHub Desktop.
Am I drunk or does this make sense?
struct WeakEnum<Enum: RawRepresentable>: Codable where Enum: Codable & Equatable, Enum.RawValue: Codable {
let rawValue: Enum.RawValue
let value: Enum?
init(rawValue: Enum.RawValue) {
self.rawValue = rawValue
self.value = Enum.init(rawValue: rawValue)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(Enum.RawValue.self)
self.init(rawValue: raw)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
func ==<T: RawRepresentable>(lhs: WeakEnum<T>, rhs: T) -> Bool {
return lhs == rhs
}
// ...
enum ModuleType: String {
case goal="GOAL", generalNotes="GENERAL_NOTES"
}
// ...
var someGoal = WeakEnum<ModuleType>(rawValue: "GOAL")
log.debug("\(someGoal.value), \(someGoal == .goal)")
var someUnknownThing = WeakEnum<ModuleType>(rawValue: "NOT_IN_ENUM")
log.debug("\(someUnknownThing.value), \(someUnknownThing == .goal)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment