Search code examples
swiftclassswift5

What is the extension signature for this .encode?


I am encoding all objects of a core data entity to JSON.

I have these lines on the core data entity extension...

public func encode(to encoder:Encoder) throws {
  var container = encoder.container(keyedBy: CodingKeys.self)
  try container.encode(name, forKey: .name)
  ...
}

I would like to create an extension for the .encode part on the container.encode part, so I can intercept it and change as I like..

I see this .encode has the following signature

public mutating func encode<T>(_ value: T, forKey key: KeyedEncodingContainer<K>.Key) throws where T : Encodable

ant that this belongs to

public struct KeyedEncodingContainer<K> : KeyedEncodingContainerProtocol where K : CodingKey {

If I want to override this encode of KeyedEncodingContainer, how should I write the extension header?

This is me blindly showing what I need...

extension KeyedEncodingContainer<K> : KeyedEncodingContainerProtocol where K : CodingKey {
  override func encode<T>(_ value: T, forKey key: Self.Key) throws where T : Encodable
    // stuff here
  }
}

In other words, I need to replace that encode with mine. Is that possible?

According to @shadowrun, I cannot extend that, because it is a struct.

So, suppose I create a class called EncodingNormalized like this one that is incorrect.

class EncodingNormalized {
  class func encode(container:KeyedEncodingContainer<Key> where Key : CodingKey) {
  }
}

I still need the class and the func encode signatures. Not that easy.


Solution

  • because I want to intercept the value as it is being encoded to change the format to what I want. Example: dates are being encoded as numbers and I need them as string with a specific format.

    If you're dealing with a JSONEncoder, set the dateEncodingStrategy on the encoder to give you dates in the format you want.

    If you're not dealing with JSONEncoder, and you're also dealing with other custom formatting things other than dates, then you do it manually inside the encode(to: ) implementation (e.g. convert something else to a string, then encode the string).