Swift添加枚举后原Codable结构体丢失协议兼容,指定CodingKeys仍报错?
问题根因
你自定义CodingKeys排除character属性后,Swift 自动合成Decodable协议实现的逻辑仍不满足要求:character是不可变存储属性,既没有声明默认初始值,也没有被纳入解码字段列表,自动生成的初始化方法无法为它完成赋值,因此依然会抛出不遵守Decodable协议的报错。
解决方案
根据你的业务需求选以下任意一种即可:
方案1:让Character枚举直接支持Codable
如果你的业务本来就需要序列化/反序列化character字段,直接给无关联值的枚举声明遵守Codable即可,Swift 会自动合成编解码逻辑,不需要改CodingKeys:
enum Character: Codable { case nice, rude }
方案2:给character属性设置默认值
如果不需要序列化character,直接给它加默认初始值,自动合成的Codable逻辑会直接用默认值为它赋值:
struct Person: Codable { let name: String let age: Int let location: String // 给不可变属性加默认值 let character: Character = .nice } // 可以保留你写的CodingKeys排除character字段 extension Person { private enum CodingKeys: CodingKey { case name, age, location } }
方案3:手动实现Decodable初始化方法
如果character的默认值需要在解码时动态确定,就手动实现初始化方法,自行处理所有属性的赋值:
extension Person: Decodable { private enum CodingKeys: CodingKey { case name, age, location } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) age = try container.decode(Int.self, forKey: .age) location = try container.decode(String.self, forKey: .location) // 按需给character赋值即可 character = .nice } }
内容的提问来源于stack exchange,提问作者Sergio Bost
相关产品推荐
相关产品推荐

