: Int, Codable or : String, Codable. For associated values in Swift 5.5+, Codable synthesis works automatically. For older versions, implement init(from:) and encode(to:) manually using keyed containers.Why this happens
Swift enums don’t automatically conform to Decodable or Codable when they have associated values or when you need custom JSON representations. The compiler can synthesize conformance for simple raw-value enums (backed by Int, String, etc.), but associated-value enums require explicit implementation because the JSON structure must represent both the case name and its payload.
Prior to Swift 5.5, you had to write manual init(from:) and encode(to:) methods. Since Swift 5.5 (Xcode 13+), the compiler synthesizes Codable for enums with associated values as long as each associated value has a label, mapping each case to a keyed dictionary in JSON.
How to fix it
1. Raw-value enums (simplest)
Add a raw-value type (Int or String) and Codable to the enum declaration. The compiler handles everything.
import Foundation
enum PostType: Int, Codable {
case image = 0
case video = 1
case audio = 2
}
// Or with String raw values
enum PostType: String, Codable {
case image
case video
case audio
}
// Usage
let json = "\"image\"" // String raw value
let data = Data(json.utf8)
let decoded = try JSONDecoder().decode(PostType.self, from: data)
print(decoded) // image
2. Decode a bare JSON value (iOS 13.3+, macOS 15.1+)
When the JSON is a single value (not an object/array), decode the enum directly.
enum PostType: Int, Codable {
case count = 4
}
let json = "4"
let data = Data(json.utf8)
let decoded = try JSONDecoder().decode(PostType.self, from: data)
print(decoded) // count
3. Enums with associated values — automatic synthesis (Swift 5.5+)
Label every associated value. The compiler generates a keyed container where the case name is the key.
enum Rotation: Codable {
case zAxis(angle: Double, speed: Int)
case xAxis(angle: Double)
}
let json = #"{"zAxis":{"angle":90,"speed":5}}"#
let data = Data(json.utf8)
let decoded = try JSONDecoder().decode(Rotation.self, from: data)
print(decoded) // zAxis(angle: 90.0, speed: 5)
4. Enums with associated values — manual implementation (pre-Swift 5.5 or custom format)
Define a CodingKeys enum for each case, then switch on the container in init(from:) and encode(to:).
enum PostType: Codable {
case count(number: Int)
case title(String)
private enum CodingKeys: String, CodingKey {
case count
case title
}
enum DecodingError: Error {
case invalidFormat
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? container.decode(Int.self, forKey: .count) {
self = .count(number: value)
return
}
if let value = try? container.decode(String.self, forKey: .title) {
self = .title(value)
return
}
throw DecodingError.invalidFormat
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .count(let number):
try container.encode(number, forKey: .count)
case .title(let value):
try container.encode(value, forKey: .title)
}
}
}
// Encoding example
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let count = PostType.count(number: 42)
let countData = try encoder.encode(count)
print(String(data: countData, encoding: .utf8)!)
// {
// "count" : 42
// }
How to prevent it
- Prefer raw-value enums (
Int/String) when the JSON schema is fixed and simple. - Label all associated values (
case foo(bar: Int)) to enable automaticCodablesynthesis in Swift 5.5+. - Keep manual
CodingKeysin sync with case names; a typo produces a runtime decoding failure. - Use
JSONEncoder.outputFormatting = .prettyPrintedduring development to inspect the generated JSON structure.
FAQ
Can I decode an enum from a plain integer or string without a wrapper object?
Yes. Since iOS 13.3/macOS 15.1, JSONDecoder supports top-level fragments. A raw-value enum like enum E: Int, Codable { case one = 1 } decodes directly from "1".
Why does automatic synthesis fail for my associated-value enum?
Every associated value must have an explicit label. case foo(Int) won’t synthesize; case foo(value: Int) will. Also, all associated value types must themselves be Codable.
How do I customize the JSON key for a specific case?
In manual implementations, change the CodingKeys raw value: case count = "item_count". With automatic synthesis (Swift 5.5+), you cannot customize keys without falling back to manual encode(to:)/init(from:).
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.
