⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

Codable 中的 super 属性编码策略

在继承体系中正确编解码父类属性,避免 JSON 扁平化冲突。 · 难度:入门 · +10XP

Codable 中的 super 属性编码策略

Swift 的 Codable 默认只编码当前类的存储属性,若父类也遵循 Codable,子类编码时会自动调用 super.encode(to:)。但父类与子类可能有同名属性,导致 JSON 覆盖。本教程将深入 decode 与 encode 的 super 调用链,并介绍通过编码键嵌套(nestedContainer)或自定义 encodingUserInfo 来避免冲突,确保多层级继承时的数据完整性。

class Vehicle: Codable {
    var wheels: Int = 4
}

final class Car: Vehicle { var brand: String = "" enum CodingKeys: CodingKey { case brand } override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(brand, forKey: .brand) try super.encode(to: encoder) } }

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 177 篇
0 完成
🔥 0