SoFunction
Updated on 2025-04-11

Detailed explanation of Swift's process of using codec library Codable

Codable is a new codec library introduced by Swift, making it easier for developers to parse JSON or plist files. Supports enumeration, structure and classes.

Codable protocol definition

Codable represents a type that can be decoded and encoded in both Decodable and Encodable protocols.

typealias Codable = Decodable & Encodable
public protocol Decodable {
    public init(from decoder: Decoder) throws
}
public protocol Encodable {
    public func encode(to encoder: Encoder) throws
}

Codable was introduced in Swift 4 and includes the Encoder and Decoder protocols and their two implementations: JSONEncoder, JSONDecoder and PropertyListEncoder, and PropertyListDecoder.

Among them, Codable and its related protocols are placed in the standard library, while the specific Encoder and Decoder classes are placed in the Foundation framework.

Conversion of JSON and model

Apple providesJSONEncoder andJSONDecoder These two structures are convenient for converting each other between JSON data and custom models. Apple can use some system-private mechanisms to achieve conversion without passingOC Runtime

As long as your data type complies with the Codable protocol, you can use the codec provided by the system to code.

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

Decoding (JSON Data -> Model):

let user = JSONDecoder().decode(, from: jsonData)

Coding (Model -> JSON Data):

let jsonData = JSONEncoder().encode(user)

Dictionary and model mutual conversion

Convert the model to Data using JSONEncoder's encode, and then deserialize it into a Dictionary object using JSONSerialization.

struct User: Codable {
    var name: String?
    var age: Int?
    static func convertFromDict(dict: NSDictionary) -> User? {
        var user: User?
        do {
            let data = try (withJSONObject: dict, options: [])
            let decoder = JSONDecoder()
            user = try (, from: data)
        } catch {
            print(error)
        }
        return user
    }
    func convertToDict() -> NSDictionary? {
        var dict: NSDictionary?
        do {
            let encoder = JSONEncoder()
            let data = try (self)
            dict = try (with: data, options: .allowFragments) as? NSDictionary
        } catch {
            print(error)
        }
        return dict
    }
}

This is the end of this article about Swift's use of codec library Codable. For more related content of Codable in Swift, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!