Skip to content

Instantly share code, notes, and snippets.

@lalkrishna
Last active January 17, 2022 12:03
Show Gist options
  • Save lalkrishna/1af15762e50697910fae5ae209a492da to your computer and use it in GitHub Desktop.
Save lalkrishna/1af15762e50697910fae5ae209a492da to your computer and use it in GitHub Desktop.
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