Swift:为同一Encodable结构体使用多种CodingKey类型
问题:为Lookup结构体实现通用编码函数,支持任意CodingKey类型
我正尝试为如下Lookup结构体编写一个统一的编码函数:
struct Lookup: Encodable { var id: Int var name: String enum StateCodingKeys: String, CodingKey { case id = "stateId" case name = "stateName" } enum CityCodingKeys: String, CodingKey { case id = "cityId" case name = "cityName" } func encode(to encoder: Encoder, type: StateCodingKeys.Type) throws { var container = encoder.container(keyedBy: type) try container.encode(id, forKey: .id) try container.encode(name, forKey: .name) } }
当前自定义encode函数仅接收StateCodingKeys.Type作为参数,我希望让该函数能够接受任意CodingKey类型(如CityCodingKeys枚举),请问是否有可行的实现方式?
解决方案
可以通过自定义协议约束实现通用的编码函数,具体步骤如下:
- 定义一个继承自
CodingKey的协议,强制要求实现id和name两个静态关联值,确保传入的CodingKey类型必须包含这两个字段:
protocol LookupCodingKey: CodingKey { static var id: Self { get } static var name: Self { get } }
- 让现有的
StateCodingKeys和CityCodingKeys遵循这个协议(它们本身已经满足字段要求,只需声明遵循即可):
enum StateCodingKeys: String, LookupCodingKey { case id = "stateId" case name = "stateName" } enum CityCodingKeys: String, LookupCodingKey { case id = "cityId" case name = "cityName" }
- 修改自定义encode函数的参数类型为
LookupCodingKey.Type,并通过类型本身获取对应的key值:
func encode(to encoder: Encoder, type: LookupCodingKey.Type) throws { var container = encoder.container(keyedBy: type) try container.encode(id, forKey: type.id) try container.encode(name, forKey: type.name) }
这样修改后,你就可以传入任意遵循LookupCodingKey协议的CodingKey类型,示例调用:
let stateLookup = Lookup(id: 1, name: "California") let cityLookup = Lookup(id: 100, name: "Los Angeles") // 用StateCodingKeys编码 let stateEncoder = JSONEncoder() try stateLookup.encode(to: stateEncoder, type: StateCodingKeys.self) // 用CityCodingKeys编码 let cityEncoder = JSONEncoder() try cityLookup.encode(to: cityEncoder, type: CityCodingKeys.self)
补充说明
如果不需要严格约束CodingKey的字段(愿意承担运行时错误风险),也可以直接将函数参数改为CodingKey.Type,但此时需要通过字符串字面量获取key,这种方式依赖CodingKey的stringValue与case名称一致,可靠性较低:
func encode(to encoder: Encoder, type: CodingKey.Type) throws { guard let idKey = type.init(stringValue: "id"), let nameKey = type.init(stringValue: "name") else { throw EncodingError.invalidValue("", .init(codingPath: [], debugDescription: "CodingKey类型不包含id或name字段")) } var container = encoder.container(keyedBy: type) try container.encode(id, forKey: idKey) try container.encode(name, forKey: nameKey) }
内容的提问来源于stack exchange,提问作者JAHelia
相关产品推荐
相关产品推荐

