gpt4 book ai didi

swift - 如何将协议(protocol)属性默认实现编码为字典

转载 作者:行者123 更新时间:2023-11-28 11:34:39 26 4
gpt4 key购买 nike

我想从具有默认实现属性的可编码结构创建字典。

struct MyStruct: MyStructProtocol {
var value: String
}

该结构实现了一个协议(protocol)。该协议(protocol)有两个变量。一个变量有一个默认实现。

protocol MyStructProtocol: Encodable {
var defaultValue: String { get }
var value: String { set get }
}

extension MyStructProtocol {
var defaultValue: String { return "my-default-value" }
}

为此,我使用了来自 How can I use Swift’s Codable to encode into a dictionary?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"]

最佳答案

合成编码器只考虑结构中的成员,不考虑协议(protocol)扩展中的任何属性或计算属性。

您必须编写自定义初始化程序。而且我更愿意让结构采用 Encodable 而不是协议(protocol)。

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 { ...

关于swift - 如何将协议(protocol)属性默认实现编码为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55850119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com