How should I structure domain models for Codable?

When structuring domain models for Codable in Swift, it's important to adopt a clear and organized approach to ensure your data is easily manageable and maintainable. The following example showcases how to create a simple model representing a User, along with an Address model, demonstrating various properties and their types to facilitate the encoding and decoding process.


    import Foundation

    // Address Model
    struct Address: Codable {
        var street: String
        var city: String
        var state: String
        var zipCode: String
    }

    // User Model
    struct User: Codable {
        var id: Int
        var name: String
        var email: String
        var address: Address
        
        private enum CodingKeys: String, CodingKey {
            case id, name, email, address
        }
    }

    // Example JSON
    let jsonString = """
    {
        "id": 1,
        "name": "John Doe",
        "email": "john.doe@example.com",
        "address": {
            "street": "123 Main St",
            "city": "Anytown",
            "state": "CA",
            "zipCode": "12345"
        }
    }
    """
    let jsonData = jsonString.data(using: .utf8)!
    
    do {
        let user = try JSONDecoder().decode(User.self, from: jsonData)
        print(user)
    } catch {
        print("Failed to decode JSON: \(error)")
    }
    

Swift Codable domain models JSON encoding JSON decoding Swift structs data modeling