codable-patterns by dpearson2699/swift-ios-skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill codable-patterns使用 Codable(Encodable & Decodable)配合 JSONEncoder、JSONDecoder 及相关 API 来编码和解码 Swift 类型。目标版本为 Swift 6.2 / iOS 26+。
当所有存储属性本身都是 Codable 时,编译器会自动合成遵循:
struct User: Codable {
let id: Int
let name: String
let email: String
let isVerified: Bool
}
let user = try JSONDecoder().decode(User.self, from: jsonData)
let encoded = try JSONEncoder().encode(user)
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
对于只读的 API 响应,优先使用 Decodable;对于只写的请求,优先使用 Encodable。仅在双向都需要时才使用 Codable。
通过声明一个 CodingKeys 枚举来重命名 JSON 键,而无需编写自定义解码器:
struct Product: Codable {
let id: Int
let displayName: String
let imageURL: URL
let priceInCents: Int
enum CodingKeys: String, CodingKey {
case id
case displayName = "display_name"
case imageURL = "image_url"
case priceInCents = "price_in_cents"
}
}
每个存储属性都必须出现在枚举中。从 CodingKeys 中省略一个属性会将其排除在编码/解码之外——需要提供默认值或单独计算它。
重写 init(from:) 和 encode(to:) 来处理合成遵循无法处理的转换:
struct Event: Codable {
let name: String
let timestamp: Date
let tags: [String]
enum CodingKeys: String, CodingKey {
case name, timestamp, tags
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
// 将 Unix 时间戳解码为 Double,然后转换为 Date
let epoch = try container.decode(Double.self, forKey: .timestamp)
timestamp = Date(timeIntervalSince1970: epoch)
// 当键缺失时,默认为空数组
tags = try container.decodeIfPresent([String].self, forKey: .tags) ?? []
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(timestamp.timeIntervalSince1970, forKey: .timestamp)
try container.encode(tags, forKey: .tags)
}
}
使用 nestedContainer(keyedBy:forKey:) 来导航和扁平化嵌套的 JSON:
// JSON: { "id": 1, "location": { "lat": 37.7749, "lng": -122.4194 } }
struct Place: Decodable {
let id: Int
let latitude: Double
let longitude: Double
enum CodingKeys: String, CodingKey { case id, location }
enum LocationKeys: String, CodingKey { case lat, lng }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
let location = try container.nestedContainer(
keyedBy: LocationKeys.self, forKey: .location)
latitude = try location.decode(Double.self, forKey: .lat)
longitude = try location.decode(Double.self, forKey: .lng)
}
}
链式调用多个 nestedContainer 来扁平化深度嵌套的结构。对于嵌套数组,也可以使用 nestedUnkeyedContainer(forKey:)。
使用鉴别器字段解码混合类型的数组:
// JSON: [{"type":"text","content":"Hello"},{"type":"image","url":"pic.jpg"}]
enum ContentBlock: Decodable {
case text(String)
case image(URL)
enum CodingKeys: String, CodingKey { case type, content, url }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case "text":
let content = try container.decode(String.self, forKey: .content)
self = .text(content)
case "image":
let url = try container.decode(URL.self, forKey: .url)
self = .image(url)
default:
throw DecodingError.dataCorruptedError(
forKey: .type, in: container,
debugDescription: "Unknown type: \(type)")
}
}
}
let blocks = try JSONDecoder().decode([ContentBlock].self, from: jsonData)
配置 JSONDecoder.dateDecodingStrategy 以匹配你的 API:
let decoder = JSONDecoder()
// ISO 8601 (例如:"2024-03-15T10:30:00Z")
decoder.dateDecodingStrategy = .iso8601
// Unix 时间戳(秒为单位,例如:1710499800)
decoder.dateDecodingStrategy = .secondsSince1970
// 自定义 DateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
decoder.dateDecodingStrategy = .formatted(formatter)
// 自定义闭包以处理多种格式
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
if let date = ISO8601DateFormatter().date(from: string) { return date }
throw DecodingError.dataCorruptedError(
in: container, debugDescription: "Cannot decode date: \(string)")
}
在 JSONEncoder 上设置匹配的策略:encoder.dateEncodingStrategy = .iso8601
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64 // Base64 编码的 Data 字段
decoder.keyDecodingStrategy = .convertFromSnakeCase // snake_case -> camelCase
// {"user_name": "Alice"} 映射到 `var userName: String` -- 无需 CodingKeys
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.keyEncodingStrategy = .convertToSnakeCase
默认情况下,一个无效元素会导致整个数组解码失败。使用包装器来跳过无效元素:
struct LossyArray<Element: Decodable>: Decodable {
let elements: [Element]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var elements: [Element] = []
while !container.isAtEnd {
if let element = try? container.decode(Element.self) {
elements.append(element)
} else {
_ = try? container.decode(AnyCodableValue.self) // 跳过坏元素
}
}
self.elements = elements
}
}
private struct AnyCodableValue: Decodable {}
使用 singleValueContainer() 包装基本类型以确保类型安全:
struct UserID: Codable, Hashable {
let rawValue: String
init(_ rawValue: String) { self.rawValue = rawValue }
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
rawValue = try container.decode(String.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
// JSON: "usr_abc123" 直接解码为 UserID
使用 decodeIfPresent 配合空值合并操作符来提供默认值:
struct Settings: Decodable {
let theme: String
let fontSize: Int
let notificationsEnabled: Bool
enum CodingKeys: String, CodingKey {
case theme, fontSize = "font_size"
case notificationsEnabled = "notifications_enabled"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
theme = try container.decodeIfPresent(String.self, forKey: .theme) ?? "system"
fontSize = try container.decodeIfPresent(Int.self, forKey: .fontSize) ?? 16
notificationsEnabled = try container.decodeIfPresent(
Bool.self, forKey: .notificationsEnabled) ?? true
}
}
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
// 非标准浮点数(NaN、Infinity 不是有效的 JSON)
encoder.nonConformingFloatEncodingStrategy = .convertToString(
positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN")
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN")
let plistEncoder = PropertyListEncoder()
plistEncoder.outputFormat = .xml // 或 .binary
let data = try plistEncoder.encode(settings)
let decoded = try PropertyListDecoder().decode(Settings.self, from: data)
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse,
(200...299).contains(http.statusCode) else {
throw APIError.invalidResponse
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(User.self, from: data)
}
// 用于包装响应的通用 API 信封
struct APIResponse<T: Decodable>: Decodable {
let data: T
let meta: Meta?
struct Meta: Decodable { let page: Int; let totalPages: Int }
}
let users = try decoder.decode(APIResponse<[User]>.self, from: data).data
Codable 结构体可以作为复合属性在 SwiftData 模型中使用。在 iOS 18+ 中,SwiftData 原生支持它们,无需显式的 @Attribute(.transformable):
struct Address: Codable {
var street: String
var city: String
var zipCode: String
}
@Model class Contact {
var name: String
var address: Address? // Codable 结构体作为复合属性存储
init(name: String, address: Address? = nil) {
self.name = name; self.address = address
}
}
通过 RawRepresentable 为 @AppStorage 存储 Codable 值:
struct UserPreferences: Codable {
var showOnboarding: Bool = true
var accentColor: String = "blue"
}
extension UserPreferences: RawRepresentable {
init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let decoded = try? JSONDecoder().decode(Self.self, from: data)
else { return nil }
self = decoded
}
var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let string = String(data: data, encoding: .utf8)
else { return "{}" }
return string
}
}
struct SettingsView: View {
@AppStorage("userPrefs") private var prefs = UserPreferences()
var body: some View {
Toggle("显示引导页", isOn: $prefs.showOnboarding)
}
}
1. 未处理缺失的可选键:
// 不要这样做——如果键不存在会崩溃
let value = try container.decode(String.self, forKey: .bio)
// 应该这样做——对于缺失的键返回 nil
let value = try container.decodeIfPresent(String.self, forKey: .bio) ?? ""
2. 一个元素无效导致整个数组失败:
// 不要这样做——一个坏元素导致整个解码失败
let items = try container.decode([Item].self, forKey: .items)
// 应该这样做——使用 LossyArray 或单独解码元素
let items = try container.decode(LossyArray<Item>.self, forKey: .items).elements
3. 日期策略不匹配:
// 不要这样做——默认策略期望 Double,但 API 发送的是 ISO 字符串
let decoder = JSONDecoder() // dateDecodingStrategy 默认为 .deferredToDate
// 应该这样做——设置策略以匹配你的 API 格式
decoder.dateDecodingStrategy = .iso8601
4. 强制解包解码出的可选值:
// 不要这样做
let user = try? decoder.decode(User.self, from: data)
print(user!.name)
// 应该这样做
guard let user = try? decoder.decode(User.self, from: data) else { return }
5. 在只需要 Decodable 时使用 Codable:
// 不要这样做——不必要地限制类型也必须遵循 Encodable
struct APIResponse: Codable { let id: Int; let message: String }
// 应该这样做——对于只读的 API 响应使用 Decodable
struct APIResponse: Decodable { let id: Int; let message: String }
6. 为简单的 snake_case API 手动编写 CodingKeys:
// 不要这样做——为每个模型编写冗长的样板代码
enum CodingKeys: String, CodingKey {
case userName = "user_name"
case avatarUrl = "avatar_url"
}
// 应该这样做——在解码器上配置一次
decoder.keyDecodingStrategy = .convertFromSnakeCase
DecodabledecodeIfPresent 配合默认值keyDecodingStrategy = .convertFromSnakeCase 而非手动编写 CodingKeysdateDecodingStrategy 与 API 日期格式匹配init(from:) 验证和转换数据,而不是在解码后进行修复JSONEncoder.outputFormatting 包含 .sortedKeys 以获得确定性的测试输出singleValueContainer 以获得简洁的 JSONAPIResponse<T> 包装器来处理一致的 API 信封@AppStorage 的 Codable 类型遵循 RawRepresentableCodable 结构体每周安装量
252
代码仓库
GitHub 星标数
269
首次出现
2026年3月8日
安全审计
安装于
codex251
opencode249
github-copilot249
kimi-cli249
gemini-cli249
amp249
Encode and decode Swift types using Codable (Encodable & Decodable) with JSONEncoder, JSONDecoder, and related APIs. Targets Swift 6.2 / iOS 26+.
When all stored properties are themselves Codable, the compiler synthesizes conformance automatically:
struct User: Codable {
let id: Int
let name: String
let email: String
let isVerified: Bool
}
let user = try JSONDecoder().decode(User.self, from: jsonData)
let encoded = try JSONEncoder().encode(user)
Prefer Decodable for read-only API responses and Encodable for write-only. Use Codable only when both directions are required.
Rename JSON keys without writing a custom decoder by declaring a CodingKeys enum:
struct Product: Codable {
let id: Int
let displayName: String
let imageURL: URL
let priceInCents: Int
enum CodingKeys: String, CodingKey {
case id
case displayName = "display_name"
case imageURL = "image_url"
case priceInCents = "price_in_cents"
}
}
Every stored property must appear in the enum. Omitting a property from CodingKeys excludes it from encoding/decoding -- provide a default value or compute it separately.
Override init(from:) and encode(to:) for transformations the synthesized conformance cannot handle:
struct Event: Codable {
let name: String
let timestamp: Date
let tags: [String]
enum CodingKeys: String, CodingKey {
case name, timestamp, tags
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
// Decode Unix timestamp as Double, convert to Date
let epoch = try container.decode(Double.self, forKey: .timestamp)
timestamp = Date(timeIntervalSince1970: epoch)
// Default to empty array when key is missing
tags = try container.decodeIfPresent([String].self, forKey: .tags) ?? []
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(timestamp.timeIntervalSince1970, forKey: .timestamp)
try container.encode(tags, forKey: .tags)
}
}
Use nestedContainer(keyedBy:forKey:) to navigate and flatten nested JSON:
// JSON: { "id": 1, "location": { "lat": 37.7749, "lng": -122.4194 } }
struct Place: Decodable {
let id: Int
let latitude: Double
let longitude: Double
enum CodingKeys: String, CodingKey { case id, location }
enum LocationKeys: String, CodingKey { case lat, lng }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
let location = try container.nestedContainer(
keyedBy: LocationKeys.self, forKey: .location)
latitude = try location.decode(Double.self, forKey: .lat)
longitude = try location.decode(Double.self, forKey: .lng)
}
}
Chain multiple nestedContainer calls to flatten deeply nested structures. Also use nestedUnkeyedContainer(forKey:) for nested arrays.
Decode arrays of mixed types using a discriminator field:
// JSON: [{"type":"text","content":"Hello"},{"type":"image","url":"pic.jpg"}]
enum ContentBlock: Decodable {
case text(String)
case image(URL)
enum CodingKeys: String, CodingKey { case type, content, url }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case "text":
let content = try container.decode(String.self, forKey: .content)
self = .text(content)
case "image":
let url = try container.decode(URL.self, forKey: .url)
self = .image(url)
default:
throw DecodingError.dataCorruptedError(
forKey: .type, in: container,
debugDescription: "Unknown type: \(type)")
}
}
}
let blocks = try JSONDecoder().decode([ContentBlock].self, from: jsonData)
Configure JSONDecoder.dateDecodingStrategy to match your API:
let decoder = JSONDecoder()
// ISO 8601 (e.g., "2024-03-15T10:30:00Z")
decoder.dateDecodingStrategy = .iso8601
// Unix timestamp in seconds (e.g., 1710499800)
decoder.dateDecodingStrategy = .secondsSince1970
// Custom DateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
decoder.dateDecodingStrategy = .formatted(formatter)
// Custom closure for multiple formats
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
if let date = ISO8601DateFormatter().date(from: string) { return date }
throw DecodingError.dataCorruptedError(
in: container, debugDescription: "Cannot decode date: \(string)")
}
Set the matching strategy on JSONEncoder: encoder.dateEncodingStrategy = .iso8601
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64 // Base64-encoded Data fields
decoder.keyDecodingStrategy = .convertFromSnakeCase // snake_case -> camelCase
// {"user_name": "Alice"} maps to `var userName: String` -- no CodingKeys needed
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.keyEncodingStrategy = .convertToSnakeCase
By default, one invalid element fails the entire array. Use a wrapper to skip invalid elements:
struct LossyArray<Element: Decodable>: Decodable {
let elements: [Element]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var elements: [Element] = []
while !container.isAtEnd {
if let element = try? container.decode(Element.self) {
elements.append(element)
} else {
_ = try? container.decode(AnyCodableValue.self) // advance past bad element
}
}
self.elements = elements
}
}
private struct AnyCodableValue: Decodable {}
Wrap primitives for type safety using singleValueContainer():
struct UserID: Codable, Hashable {
let rawValue: String
init(_ rawValue: String) { self.rawValue = rawValue }
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
rawValue = try container.decode(String.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
// JSON: "usr_abc123" decodes directly to UserID
Use decodeIfPresent with nil-coalescing to provide defaults:
struct Settings: Decodable {
let theme: String
let fontSize: Int
let notificationsEnabled: Bool
enum CodingKeys: String, CodingKey {
case theme, fontSize = "font_size"
case notificationsEnabled = "notifications_enabled"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
theme = try container.decodeIfPresent(String.self, forKey: .theme) ?? "system"
fontSize = try container.decodeIfPresent(Int.self, forKey: .fontSize) ?? 16
notificationsEnabled = try container.decodeIfPresent(
Bool.self, forKey: .notificationsEnabled) ?? true
}
}
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
// Non-conforming floats (NaN, Infinity are not valid JSON)
encoder.nonConformingFloatEncodingStrategy = .convertToString(
positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN")
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN")
let plistEncoder = PropertyListEncoder()
plistEncoder.outputFormat = .xml // or .binary
let data = try plistEncoder.encode(settings)
let decoded = try PropertyListDecoder().decode(Settings.self, from: data)
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse,
(200...299).contains(http.statusCode) else {
throw APIError.invalidResponse
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(User.self, from: data)
}
// Generic API envelope for wrapped responses
struct APIResponse<T: Decodable>: Decodable {
let data: T
let meta: Meta?
struct Meta: Decodable { let page: Int; let totalPages: Int }
}
let users = try decoder.decode(APIResponse<[User]>.self, from: data).data
Codable structs work as composite attributes in SwiftData models. In iOS 18+, SwiftData natively supports them without explicit @Attribute(.transformable):
struct Address: Codable {
var street: String
var city: String
var zipCode: String
}
@Model class Contact {
var name: String
var address: Address? // Codable struct stored as composite attribute
init(name: String, address: Address? = nil) {
self.name = name; self.address = address
}
}
Store Codable values via RawRepresentable for @AppStorage:
struct UserPreferences: Codable {
var showOnboarding: Bool = true
var accentColor: String = "blue"
}
extension UserPreferences: RawRepresentable {
init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let decoded = try? JSONDecoder().decode(Self.self, from: data)
else { return nil }
self = decoded
}
var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let string = String(data: data, encoding: .utf8)
else { return "{}" }
return string
}
}
struct SettingsView: View {
@AppStorage("userPrefs") private var prefs = UserPreferences()
var body: some View {
Toggle("Show Onboarding", isOn: $prefs.showOnboarding)
}
}
1. Not handling missing optional keys:
// DON'T -- crashes if key is absent
let value = try container.decode(String.self, forKey: .bio)
// DO -- returns nil for missing keys
let value = try container.decodeIfPresent(String.self, forKey: .bio) ?? ""
2. Failing entire array when one element is invalid:
// DON'T -- one bad element kills the whole decode
let items = try container.decode([Item].self, forKey: .items)
// DO -- use LossyArray or decode elements individually
let items = try container.decode(LossyArray<Item>.self, forKey: .items).elements
3. Date strategy mismatch:
// DON'T -- default strategy expects Double, but API sends ISO string
let decoder = JSONDecoder() // dateDecodingStrategy defaults to .deferredToDate
// DO -- set strategy to match your API format
decoder.dateDecodingStrategy = .iso8601
4. Force-unwrapping decoded optionals:
// DON'T
let user = try? decoder.decode(User.self, from: data)
print(user!.name)
// DO
guard let user = try? decoder.decode(User.self, from: data) else { return }
5. Using Codable when only Decodable is needed:
// DON'T -- unnecessarily constrains the type to also be Encodable
struct APIResponse: Codable { let id: Int; let message: String }
// DO -- use Decodable for read-only API responses
struct APIResponse: Decodable { let id: Int; let message: String }
6. Manual CodingKeys for simple snake_case APIs:
// DON'T -- verbose boilerplate for every model
enum CodingKeys: String, CodingKey {
case userName = "user_name"
case avatarUrl = "avatar_url"
}
// DO -- configure once on the decoder
decoder.keyDecodingStrategy = .convertFromSnakeCase
Decodable only when encoding is not neededdecodeIfPresent used with defaults for optional or missing keyskeyDecodingStrategy = .convertFromSnakeCase used instead of manual CodingKeys for simple snake_case APIsdateDecodingStrategy matches the API date formatinit(from:) validates and transforms data instead of post-decode fixupsJSONEncoder.outputFormatting includes .sortedKeys for deterministic test outputsingleValueContainer for clean JSONAPIResponse<T> wrapper used for consistent API envelope handlingWeekly Installs
252
Repository
GitHub Stars
269
First Seen
Mar 8, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex251
opencode249
github-copilot249
kimi-cli249
gemini-cli249
amp249
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装
@AppStorage Codable types conform to RawRepresentableCodable structs