Encoding and decoding enum with no associated values in Swift

Hullo, I need to encode and decode a simple enum with no associated values, but I only find examples with associated values and someone say a bare enum would be automatically Codable, what the compiler does not agree upon. This is my code sale that looks very clumsy, though:
Code Block
enum MeditationItem: Codable, CodingKey{
case morning
case evening
case dropIn
case dropOut
case intermediate
case single
case supported
case walking
func nameForKind()->String{
switch self{
case .morning: return "Morning"
case .evening: return "Evening"
case .dropIn: return "dropIn"
case .dropOut: return "dropOut"
case .intermediate: return "intermediate"
case .single: return "Single"
case .supported: return "Supported"
case .walking: return "Walking"
}
}
init(from decoder: Decoder) throws {
do {
let container = try decoder.container(keyedBy: MeditationItem.self)
do {
let morning = try container.decode(MeditationItem.self, forKey: .morning)
self=morning
} catch {
let evening = try container.decode(MeditationItem.self, forKey: .evening)
self=evening
}
}

What is the most sleek way to encode and decode an enum with no associated values?
Just add raw value type to the definition.
Code Block
enum MeditationItem: Int, Codable, CodingKey{ //<- Please do not miss `Int` in this line.
case morning
case evening
case dropIn
case dropOut
case intermediate
case single
case supported
case walking
func nameForKind()->String{
switch self{
case .morning: return "Morning"
case .evening: return "Evening"
case .dropIn: return "dropIn"
case .dropOut: return "dropOut"
case .intermediate: return "intermediate"
case .single: return "Single"
case .supported: return "Supported"
case .walking: return "Walking"
}
}
}


You can use String if you prefer:
Code Block
enum MeditationItem: String, Codable {
case morning = "Morning"
case evening = "Evening"
case dropIn
case dropOut
case intermediate
case single = "Single"
case supported = "Supported"
case walking = "Walking"
func nameForKind() -> String {
return self.rawValue
}
}



I do not understand why you added conformance to CodingKey, so I keep it in the example code above, but do you really need it?
Encoding and decoding enum with no associated values in Swift
 
 
Q