如何在JSONDecoder解码SomeAPI结构体后自动执行额外操作?
实现方法
Swift 中结构体不存在继承关系(你示例里的 super 是无效写法),要实现解码完成后自动执行代码,最直接的方式是自定义 Codable 的解码初始化器——JSONDecoder 解码每个实例时都会调用 init(from decoder: Decoder) 方法,你可以在这个方法里完成解码后执行自定义逻辑。
方案1:基础自定义初始化器
手动实现 init(from:),先完成所有属性的解码,再执行你需要的操作:
public struct SomeAPI: Codable { public let a: String public let b: String public let c: String public let d: String // 自定义解码初始化器 public init(from decoder: Decoder) throws { // 先解码所有属性 let container = try decoder.container(keyedBy: CodingKeys.self) a = try container.decode(String.self, forKey: .a) b = try container.decode(String.self, forKey: .b) c = try container.decode(String.self, forKey: .c) d = try container.decode(String.self, forKey: .d) // 解码完成后执行自定义逻辑 print("I just decoded one of the thingies! a is \(a)") // 这里可以添加任何操作:数据校验、缓存写入、状态同步等 } // 编译器会自动生成CodingKeys,这里显式写出是为了清晰 private enum CodingKeys: String, CodingKey { case a, b, c, d } }
当你批量解码数组时,每个实例都会自动触发初始化器里的逻辑,无需手动遍历处理:
let someAPIs = try? JSONDecoder().decode([SomeAPI].self, from: data)
方案2:灵活的动态逻辑(可选)
如果需要根据不同解码场景执行不同操作,可以借助 JSONDecoder 的 userInfo 字典传递自定义逻辑,避免修改结构体内部代码:
// 定义自定义userInfo键 extension CodingUserInfoKey { static let postDecodeAction = CodingUserInfoKey(rawValue: "postDecodeAction")! } public struct SomeAPI: Codable { public let a: String public let b: String public let c: String public let d: String public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) a = try container.decode(String.self, forKey: .a) b = try container.decode(String.self, forKey: .b) c = try container.decode(String.self, forKey: .c) d = try container.decode(String.self, forKey: .d) // 读取userInfo中的自定义逻辑并执行 if let action = decoder.userInfo[.postDecodeAction] as? (SomeAPI) -> Void { action(self) } } private enum CodingKeys: String, CodingKey { case a, b, c, d } } // 使用时传递自定义逻辑 let decoder = JSONDecoder() decoder.userInfo[.postDecodeAction] = { api in print("I just decoded one of the thingies! a is \(api.a)") } let someAPIs = try? decoder.decode([SomeAPI].self, from: data)
内容的提问来源于stack exchange,提问作者Fattie
相关产品推荐
相关产品推荐

