swift - 如何将协议属性默认实现编码为字典
问题描述
我想从具有默认实现属性的可编码结构中制作字典。
struct MyStruct: MyStructProtocol {
var value: String
}
该结构实现了一个协议。该协议有两个变量。一个变量具有默认实现。
protocol MyStructProtocol: Encodable {
var defaultValue: String { get }
var value: String { set get }
}
extension MyStructProtocol {
var defaultValue: String { return "my-default-value" }
}
为此,我使用如何使用 Swift 的 Codable 编码到字典Encodable
中的扩展?:
extension Encodable {
var asDictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
因此,当我实例化结构并将其“编码”为字典时:
let myStruct = MyStruct(value: "my-value")
let myStructDictionary = myStruct.asDictionary
那么defaultValue
不包括:
["value": "my-value"]
但我需要的是(包括默认值):
["defaultValue": "my-default-value", "value": "my-value"]
解决方案
合成编码器仅考虑结构中的成员,而不考虑协议扩展中的任何属性或计算属性。
您必须编写一个自定义初始化程序。而且我更愿意让结构采用Encodable
而不是协议。
struct MyStruct: MyStructProtocol, Encodable {
var value: String
private enum CodingKeys: String, CodingKey { case value, defaultValue }
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
try container.encode(defaultValue, forKey: .defaultValue)
}
}
protocol MyStructProtocol { ...
推荐阅读
- react-native - React Native 中的数据表
- docker - 将 docker 映像重置为初始状态
- python - 像 jupyter notebook 一样将 python 脚本输出转换为 pdf
- c# - ftp 发布后 Web 应用程序视图未更新(从 Net Core 1.x - 2.2 升级后)
- android - 应用程序安装在 Play 商店但未启动 Android
- python - DataFrame 合并以排除额外的索引列
- python - 使用 python 对 API 进行负载测试
- php - 如何从我无法访问的php SFTP上传文件
- python - 记录的插入次数与运行模型文件的次数一样多
- ios - 自定义 UITableView 单元格图像转换未应用于可重用单元格