Browse Questions
  • SOLID is a set of five design guidelines for maintainable OOP code: | Principle | Idea | Swift application | |--|--|--| | Single Responsibility | A type should have one reason to change | Split a…
  • Both safely unwrap optionals, but they differ in scope and intent.
  • Codable is a type alias for Encodable & Decodable.
  • To create a custom Xcode File Template from scratch, create a .xctemplate directory inside ~/Library/Developer/Xcode/Templates/File Templates/<Category>/, add a TemplateInfo.plist declaring the…

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
    }
}