首页 > 解决方案 > 这个 .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 encodeKeyedEncodingContaine我应该如何编写扩展头?

这是我盲目地展示我需要的东西......

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 编码签名。没那么容易。

标签: swiftclassswift5

解决方案


因为我想截取值,因为它正在被编码以将格式更改为我想要的格式。示例:日期被编码为数字,我需要它们作为具有特定格式的字符串。

如果您正在处理JSONEncoder,请在编码器上设置 ,dateEncodingStrategy以您想要的格式为您提供日期。

如果您不处理JSONEncoder,并且您还处理除日期之外的其他自定义格式设置,那么您可以在实现中手动encode(to: )执行(例如将其他内容转换为字符串,然后对字符串进行编码)。


推荐阅读