Created
April 23, 2018 16:35
-
-
Save vietstone-ng/c223a3033b23a5daa74e198f9983a047 to your computer and use it in GitHub Desktop.
Enum with raw values working with Codable
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
enum SongLanguage: Int { | |
case vietnamese = 0 | |
case english = 1 | |
case thai = 2 | |
case unknown = -1 | |
} | |
extension SongLanguage: Codable { | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.unkeyedContainer() | |
try container.encode(self.rawValue) | |
} | |
public init(from decoder: Decoder) throws { | |
var container = try decoder.unkeyedContainer() | |
if let rawInt = try container.decodeIfPresent(Int.self) { | |
self = SongLanguage(rawValue: rawInt) ?? .unknown | |
} else { | |
self = .unknown | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment