Skip to content

Instantly share code, notes, and snippets.

@vietstone-ng
Created April 23, 2018 16:35
Show Gist options
  • Save vietstone-ng/c223a3033b23a5daa74e198f9983a047 to your computer and use it in GitHub Desktop.
Save vietstone-ng/c223a3033b23a5daa74e198f9983a047 to your computer and use it in GitHub Desktop.
Enum with raw values working with Codable
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