SyntaxStudy
Sign Up
Swift Codable and Standard Protocols
Swift Beginner 1 min read

Codable and Standard Protocols

Swift's standard library defines several important protocols: Equatable (==), Comparable (<), Hashable (use in dictionaries/sets), CustomStringConvertible (description), and Codable (JSON encoding/decoding). Codable (= Encodable & Decodable) is synthesized automatically for types whose properties are all Codable. JSONEncoder/JSONDecoder convert between Swift types and JSON data. CodingKeys enum customizes property name mapping when JSON keys differ from Swift property names.
Example
import Foundation

// Codable with custom keys
struct User: Codable, Equatable, CustomStringConvertible {
    let id: Int
    let username: String
    let email: String
    let createdAt: Date

    var description: String { "User(\(id): \(username))" }

    enum CodingKeys: String, CodingKey {
        case id
        case username
        case email
        case createdAt = "created_at"
    }
}

// Encoding to JSON
let user = User(id: 1, username: "alice", email: "alice@example.com", createdAt: Date())
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = .prettyPrinted

if let data = try? encoder.encode(user),
   let json = String(data: data, encoding: .utf8) {
    print(json)
}

// Decoding from JSON
let jsonString = """
{"id": 2, "username": "bob", "email": "bob@example.com", "created_at": "2024-01-15T10:30:00Z"}
"""
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

if let data = jsonString.data(using: .utf8),
   let decoded = try? decoder.decode(User.self, from: data) {
    print(decoded)
}