Last active
January 17, 2022 12:03
-
-
Save lalkrishna/1af15762e50697910fae5ae209a492da to your computer and use it in GitHub Desktop.
Solve New Enum Cases. (Note: Required Swift 5.3, Refer: https://github.com/apple/swift-evolution/blob/master/proposals/0280-enum-cases-as-protocol-witnesses.md)
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
protocol UnknownCase: RawRepresentable, CaseIterable where RawValue: Equatable & Codable { | |
static var unknownCase: Self { get } | |
} | |
extension UnknownCase { | |
init(rawValue: RawValue) { | |
let value = Self.allCases.first { $0.rawValue == rawValue } | |
self = value ?? Self.unknownCase | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
let rawValue = try container.decode(RawValue.self) | |
let value = Self(rawValue: rawValue) | |
self = value ?? Self.unknownCase | |
} | |
} | |
// | |
// Usage | |
// | |
enum YourCodableEnum: Int, Codable, UnknownCase { // Conform to 'UnknownCase' protocol | |
case unknownCase // Add this case | |
case profile = 2, event = 6 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment