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)")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?