Swift's Codable: Effortless JSON & Data Parsing

Codable is a compiler magic trick that automatically converts Swift objects to and from formats like JSON. It's used constantly for parsing API responses or saving data to disk. The footgun: decoding fails if JSON keys don't exactly match your property names.
WHY IT EXISTS Before Codable, Swift developers wrote large amounts of manual, error-prone code to convert data like JSON into Swift objects. This involved checking for keys, casting types, and assigning properties one by one. This boilerplate was repetitive, brittle, and a common source of bugs.
THE MENTAL MODEL Think of Codable as a universal translator for your Swift types. By declaring that your struct or class conforms to Codable, you tell the Swift compiler: "Please automatically generate the code to convert this object to and from a serialized format like JSON for me." It's a convenient alias for two separate protocols: Encodable (Swift object -> Data) and Decodable (Data -> Swift object).
HOW IT WORKS When you add : Codable to your type, the compiler synthesizes the required methods behind the scenes. For a struct, it inspects its properties and generates code that expects to find matching keys in the source data. It automatically handles primitive types like String, Int, and Bool, as well as collections like Array and Dictionary, and even other nested Codable types. You simply provide the data and the type, and a JSONDecoder or JSONEncoder object does the work.
WHEN TO USE IT Use Codable whenever you need to serialize or deserialize structured data. Its primary use cases are networking, like parsing a JSON response from a REST API into your app's models, and persistence, such as saving user preferences or complex objects to UserDefaults or a file on disk.
WHEN NOT TO USE IT If your JSON keys don't match your Swift property names (e.g., first_name in JSON vs. firstName in Swift), the default implementation will fail. You must provide a custom CodingKeys enum to map the names. For highly irregular or unpredictable data structures, a manual parsing approach might be more suitable. While very performant, for extremely large datasets where every nanosecond counts, a specialized parser might offer a slight edge, but this is a rare requirement.
ONE CANONICAL EXAMPLE To parse a JSON string like {"name": "Eiffel Tower", "height": 330} into a Swift object, you just define the type: struct Landmark: Codable { let name: String; let height: Int; }. Then, you can use JSONDecoder().decode(Landmark.self, from: jsonData) to create a Landmark instance directly from the raw JSON data, with no manual field mapping required.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.