0
0
Swiftprogramming~5 mins

Codable protocol for encoding/decoding in Swift

Choose your learning style9 modes available
Introduction

The Codable protocol helps you easily convert your Swift data into formats like JSON and back. This makes saving and sharing data simple.

When you want to save app data to a file or database.
When you need to send data over the internet in JSON format.
When you want to read data from a JSON file into your app.
When you want to convert Swift objects to a format that other apps or services understand.
Syntax
Swift
struct MyData: Codable {
    var name: String
    var age: Int
}
Use Codable on structs or classes to make them encodable and decodable.
Codable is a combination of Encodable and Decodable protocols.
Examples
This struct can now be converted to and from JSON easily.
Swift
struct Person: Codable {
    var firstName: String
    var lastName: String
    var age: Int
}
Encode a Person instance to JSON data, then decode it back to a Person.
Swift
let jsonData = try JSONEncoder().encode(person)
let personAgain = try JSONDecoder().decode(Person.self, from: jsonData)
Codable works with classes too, not just structs.
Swift
class Book: Codable {
    var title: String
    var pages: Int

    init(title: String, pages: Int) {
        self.title = title
        self.pages = pages
    }
}
Sample Program

This program creates a User, converts it to JSON text, prints it, then converts the JSON back to a User and prints the details.

Swift
import Foundation

struct User: Codable {
    var username: String
    var score: Int
}

let user = User(username: "alice", score: 42)

// Encode user to JSON
if let jsonData = try? JSONEncoder().encode(user) {
    print("JSON String:")
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }

    // Decode JSON back to User
    if let decodedUser = try? JSONDecoder().decode(User.self, from: jsonData) {
        print("Decoded User:")
        print("Username: \(decodedUser.username), Score: \(decodedUser.score)")
    }
}
OutputSuccess
Important Notes

Make sure all properties in your type are also Codable.

If you want to customize encoding or decoding, you can implement init(from:) and encode(to:) methods.

Summary

Codable makes converting Swift data to and from formats like JSON easy.

Use Codable on your structs or classes to enable this automatic conversion.

Encoding turns your data into JSON; decoding turns JSON back into your data.