Codable Swift: Complete Guide with Examples
1. What Is Codable and Why Use It?
Codable is a built-in protocol (a typealias for Encodable & Decodable) in Swift, introduced in Swift 4. It provides a declarative way to serialize and deserialize custom data types into formats like JSON, Property List (plist), and others. Instead of manually writing bulky code to convert structs to dictionaries and back, Codable automatically generates encoding/decoding logic based on your model's properties.
Why do you need it? In modern iOS/macOS development, almost every app interacts with a server API, sending and receiving data in JSON format. Without Codable, developers would have to manually write loops, check types, handle optional values, and build reverse parsers. Codable solves this by making code cleaner, safer, and significantly reducing development time. It's also the de facto standard for JSON handling in the Apple ecosystem.
Codable works through the Encodable protocol (converting Swift types to data) and the Decodable protocol (converting data to Swift types). Combining them gives you a full serialization cycle. The library is tightly integrated with JSONEncoder and JSONDecoder, the primary tools for working with JSON.
2. Setup
Codable is part of the Swift standard library (Foundation). No additional installation is required. You don't need pip, npm, CocoaPods, or Swift Package Manager to use it. Simply import Foundation in your file:
import Foundation
If you're using Swift on Linux (e.g., via Swift Package Manager), Codable is also available out of the box. Server-side frameworks like Vapor use Codable by default.
3. Quick Start — Minimal Working Example
Let's create a simple user struct and serialize/deserialize it to JSON.
import Foundation
// 1. Define a model conforming to Codable
struct User: Codable {
let id: Int
let name: String
let email: String
}
// 2. Create an instance
let user = User(id: 1, name: "Alice", email: "alice@example.com")
// 3. Encode to JSON
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // For readable output
do {
let jsonData = try encoder.encode(user)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print("JSON: \n\(jsonString)")
}
// 4. Decode back
let decoder = JSONDecoder()
let decodedUser = try decoder.decode(User.self, from: jsonData)
print("Decoded user: \(decodedUser.name), email: \(decodedUser.email)")
} catch {
print("Error: \(error)")
}
Console output:
JSON:
{
"id" : 1,
"name" : "Alice",
"email" : "alice@example.com"
}
Decoded user: Alice, email: alice@example.com
As you can see, just a few lines of code and serialization is ready.
4. Key Methods, Functions, and Classes
Let's explore the core Codable components you'll use regularly.
4.1 JSONEncoder
Signature: class JSONEncoder : NSCoder
What it does: Converts instances of types conforming to Encodable into a Data object (JSON).
Also in library
Recommendations