Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 146 ยท Structures, Classes and Enums

Codable

Learn Swift Codable - encode and decode JSON with JSONEncoder and JSONDecoder, rename keys with CodingKeys, handle optionals and dates, write custom init(from:), and read decoding errors.

Programs constantly turn their data into text or bytes and back again: saving settings, talking to a web service, writing a cache to disk. In Swift this is built into the language through two protocols, Encodable and Decodable, and their combination Codable. When you declare that a type is Codable, the compiler writes the conversion code for you, and a separate encoder such as JSONEncoder decides what the output looks like.

This split is the key idea. Your type only describes what its data is; the encoder decides how to write it (JSON, property list, or your own format). In this lesson you will work with JSON, which is what most programs need. The encoder and decoder live in Foundation, so every example imports it.

Encoding a value to JSON

Add Codable to a struct whose properties are themselves Codable (all the standard types are: String, Int, Double, Bool, Array, Dictionary, Optional, Date, URL, UUID, Data ...), then hand an instance to a JSONEncoder.

Swift Encode a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

encode(_:) returns Data, raw UTF-8 bytes, so we turn it into a String to look at it. Two formatting options help while learning: .prettyPrinted adds line breaks and indentation, and .sortedKeys makes the key order stable. Swift does not guarantee key order otherwise, and dictionaries have randomized order, so always set .sortedKeys when you compare or print output.

encode can throw, so it needs try. At the top level of main.swift you can write try without a do block: an error ends the program with a message. In real code, wrap it in do { } catch { } as shown further down.

Decoding JSON into a value

Decoding is the mirror image. You give JSONDecoder the type you expect and the bytes to read.

Swift Decode JSON text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Book.self is the type object; it tells the decoder what to build. Extra keys in the JSON that Book does not declare are ignored, so a service can add fields without breaking you. The reverse is not true: a key that Book needs but the JSON lacks is an error, as you will see below.

A full round trip (encode, then decode) is also the quickest way to copy a value deeply or to test your coding logic. Decoded values compare equal when the type is also Equatable.

Renaming keys with CodingKeys

APIs often use snake_case or other names than your properties. You describe the mapping with a nested enum called CodingKeys. Its cases match your property names, and its raw values are the JSON keys.

Swift CodingKeys for different names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The same enum drives both directions, so the encoded text uses the JSON names again. One rule to remember: if you write CodingKeys, it must list every property you want coded. A property you leave out is skipped when encoding and decoding, and then it must have a default value, otherwise the compiler cannot build the decoder.

Converting snake_case automatically

When a whole API follows one naming style, you do not need to list every key. Set a key strategy on the coder:

Swift keyDecodingStrategy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

order_id becomes orderId on the way in and back again on the way out. Use CodingKeys for the odd one out and the strategy for the general rule.

Optionals, defaults and missing keys

An Optional property is decoded as nil when its key is missing or the JSON value is null. A non-optional property with a missing key makes decoding fail.

Swift Missing key error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first decode works and prints Pen nil. For the second, the catch pattern prints missing key: price followed by the decoder's own explanation (No value associated with key CodingKeys(stringValue: "price", intValue: nil) ("price").). The final line has no catch, so the program ends with Fatal error: Error raised at top level: DecodingError.keyNotFound: Key 'price' not found in keyed decoding container. and a backtrace. The run is marked as failing: that is the lesson.

DecodingError has four cases that cover nearly everything that goes wrong: keyNotFound, typeMismatch (a number where a string was expected), valueNotFound (a null for a required value) and dataCorrupted (invalid JSON). Each carries a codingPath that says exactly where in the document the problem is. Matching these cases gives users much better messages than error.localizedDescription.

Dates

JSON has no date type, so you choose how dates are written. The default is a number of seconds, which is rarely what an API uses. The most common choice is ISO 8601 text:

Swift Dates as ISO 8601

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

timeIntervalSince1970 is the number of seconds since 1 January 1970 UTC, which makes the decoded date easy to verify. The strategy .iso8601 accepts only whole-second timestamps without fractions. For other shapes use .formatted(DateFormatter), .secondsSince1970, .millisecondsSince1970, or .custom { ... }. Set the same strategy on the encoder and decoder, or the round trip breaks.

Custom decoding with init(from:)

Sometimes the JSON shape differs from your model: values nested deeper, a number sent as a string, a field that might be absent but should default. Implement init(from:) and encode(to:) yourself and keep the rest synthesized.

Swift Custom init(from:)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A keyed container works like a dictionary of coding keys. decode(_:forKey:) throws when the key is missing; decodeIfPresent returns nil instead, which ?? turns into a default. nestedContainer steps into a sub-object. Because we declared only Decodable, we did not need to write an encoder.

Declare only the half you need. A type that only reads server responses can be Decodable; a type that only produces output can be Encodable. Codable is simply a typealias for both: typealias Codable = Decodable & Encodable.

Enums, arrays and nested types

Almost everything composes. An enum with a String or Int raw value is Codable automatically, arrays of codable things are codable, and so are dictionaries with String keys.

Swift Nested and collection types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The enum is written as its raw string ("beginner"), and the dictionary becomes a JSON object. If a JSON string does not match any case, decoding throws a dataCorrupted error rather than crashing.

Practical advice

  • Let the compiler write it. Handwrite init(from:) only when the shape really differs.
  • Decode into small models. Define one struct per JSON shape and convert into your domain types afterward. The wire format and your app model change for different reasons.
  • Handle errors by case. catch let error as DecodingError and read the codingPath for diagnostics.
  • Classes and inheritance need extra care: a subclass does not inherit synthesized conformance for its own properties. Prefer structs.
  • Do not trust input. Decoding checks structure and types, not meaning. Validate ranges and required relationships afterward.
  • Keep one encoder. Creating coders is cheap but not free; reuse one configured instance.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is Codable?

    Codable combines Encodable and Decodable. The compiler synthesizes both when all stored properties are codable.
  2. 2. A JSON document has the key "first_name" but your property is firstName. Which tools fix this?

    Either map the keys explicitly with CodingKeys or set the snake-case key strategy on the decoder.
  3. 3. What happens when a non-optional property's key is missing in the JSON?

    Missing required keys cause a thrown keyNotFound error, which you can catch and report with its coding path.
  4. 4. Why set .sortedKeys on a JSONEncoder when printing in a tutorial or test?

    Without it, key order may vary between runs, so outputs are not reproducible.
  5. 5. Which decoder call returns nil instead of throwing when a key is absent?

    decodeIfPresent is for optional values; combine it with ?? to provide a default.

Summary

  • Codable = Encodable + Decodable; the compiler synthesizes both when every stored property is codable.
  • JSONEncoder.encode(_:) returns Data; JSONDecoder.decode(_:from:) takes the target type and Data. Both are in Foundation and both throw.
  • Rename keys with a nested CodingKeys enum, or use .convertFromSnakeCase / .convertToSnakeCase for a whole API.
  • Optionals decode to nil when missing; required properties throw DecodingError.keyNotFound.
  • Choose a date strategy such as .iso8601 on both coder and decoder.
  • Write init(from:) and encode(to:) with keyed containers only for shapes the synthesized code cannot handle.

Next: CustomStringConvertible and Debug Output