Browse Questions
- They're often confused because both involve "hiding" something, but they hide different things for different reasons: - Encapsulation hides internal state to protect it from invalid mutation (an…
- Codable is a type alias for Encodable & Decodable.
- Store tokens securely in the Keychain, attach them to requests via a header, and refresh automatically when a 401 is received.
- Use a protocol for URLSession or inject a custom URLProtocol subclass that intercepts requests and returns fake responses without hitting the network.
Answer:
Codable is a type alias for Encodable & Decodable. It lets you convert Swift types to and from external formats like JSON with minimal boilerplate. The compiler auto-synthesizes the implementation if property names match the JSON keys.
Code Example:
struct User: Codable {
let id: Int
let name: String
let email: String
}
// Decoding JSON → Swift
let json = """
{ "id": 1, "name": "Alice", "email": "alice@example.com" }
""".data(using: .utf8)!
let user = try JSONDecoder().decode(User.self, from: json)
print(user.name) // "Alice"
// Encoding Swift → JSON
let encoded = try JSONEncoder().encode(user)
// Custom key mapping
struct Article: Codable {
let title: String
let publishedAt: Date
enum CodingKeys: String, CodingKey {
case title
case publishedAt = "published_at" // maps snake_case to camelCase
}
}