Swift Codable: Encode and Decode JSON Data Effortlessly

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
March 27, 2024
Working with Codable in Swift

Working with Codable in Swift

Codable is a protocol in Swift that allows you to easily encode and decode custom types to and from external representations such as JSON. This is particularly useful when working with APIs or when persisting data in your application.

Encoding with Codable

Encoding a custom object in Swift using the Codable protocol is straightforward. Simply conform your custom type to Codable, and then use an instance of a JSONEncoder to encode the object into a JSON data.

    struct Person: Codable {
        var name: String
        var age: Int
    }

    let person = Person(name: "John Doe", age: 30)

    do {
        let encoder = JSONEncoder()
        let jsonData = try encoder.encode(person)
        let jsonString = String(data: jsonData, encoding: .utf8)
        print(jsonString)
    } catch {
        print("Error encoding person: \(error)")
    }
    

    

Decoding with Codable

Decoding JSON data into a custom object is just as simple. Conform your custom type to Codable, and then use an instance of a JSONDecoder to decode JSON data into your custom object.

    let jsonString = """
    {
        "name": "Jane Smith",
        "age": 25
    }
    """
    
    let jsonData = jsonString.data(using: .utf8)!
    
    do {
        let decoder = JSONDecoder()
        let decodedPerson = try decoder.decode(Person.self, from: jsonData)
        print(decodedPerson)
    } catch {
        print("Error decoding person: \(error)")
    }
    

    

Codable makes it easy to work with JSON data in Swift, simplifying the process of encoding and decoding custom types. By conforming your custom types to Codable, you can easily serialize and deserialize data, making your code more robust and maintainable.