Last active
August 17, 2018 03:17
-
-
Save isoiphone/8132f76045253bf40b6ba9a62444b9d6 to your computer and use it in GitHub Desktop.
Am I drunk or does this make sense?
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
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