swift - 这个 .encode 的扩展签名是什么?
问题描述
我正在将核心数据实体的所有对象编码为 JSON。
我在核心数据实体扩展上有这些行......
public func encode(to encoder:Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
...
}
我想为.encode
零件上的container.encode
零件创建一个扩展,这样我就可以截取它并根据需要进行更改..
我看到这.encode
有以下签名
public mutating func encode<T>(_ value: T, forKey key: KeyedEncodingContainer<K>.Key) throws where T : Encodable
这属于的蚂蚁
public struct KeyedEncodingContainer<K> : KeyedEncodingContainerProtocol where K : CodingKey {
如果我想覆盖这个r encode
,KeyedEncodingContaine
我应该如何编写扩展头?
这是我盲目地展示我需要的东西......
extension KeyedEncodingContainer<K> : KeyedEncodingContainerProtocol where K : CodingKey {
override func encode<T>(_ value: T, forKey key: Self.Key) throws where T : Encodable
// stuff here
}
}
换句话说,我需要encode
用我的替换它。那可能吗?
根据@shadowrun,我不能扩展它,因为它是一个结构。
所以,假设我创建了EncodingNormalized
一个不正确的类,就像这样。
class EncodingNormalized {
class func encode(container:KeyedEncodingContainer<Key> where Key : CodingKey) {
}
}
我仍然需要类和 func 编码签名。没那么容易。
解决方案
因为我想截取值,因为它正在被编码以将格式更改为我想要的格式。示例:日期被编码为数字,我需要它们作为具有特定格式的字符串。
如果您正在处理JSONEncoder
,请在编码器上设置 ,dateEncodingStrategy
以您想要的格式为您提供日期。
如果您不处理JSONEncoder
,并且您还处理除日期之外的其他自定义格式设置,那么您可以在实现中手动encode(to: )
执行(例如将其他内容转换为字符串,然后对字符串进行编码)。
推荐阅读
- mocking - 无法模拟具有 @RequiredArgsConstructor 的类
- php - 如何每行只有 3 个带有动态复选框编号的复选框
- r - R:使用 ggplot 更改风险热图中的 colorPalette 颜色
- android - 视图不想更新
- html - 我应该把我的标签放在哪里以便将它放在我的弹性容器下面
- sql - 如何创建一个触发器来计算从一个表到另一个表的具有匹配 id 的字段的总和?
- html - 虽然 #navbar 宽度是 100% 并且还设置了 box-sizing ,但 navbar 比右侧的 body 宽一点,为什么?#navbar 固定并且宽度是 100%
- python - 必需的位置参数,“类型错误:缺少自我参数”
- python-3.x - 不添加所有不在字典值中的元素
- python - Python Pandas 根据条件更改值