覆盖struct中的Codable实现

有没有办法重写结构的Codable实现?

不能更改的代码:

struct obj1 : Codable {
   var values:[Int]
   ...
}

所需的JSON:

{ "x": 1, "y": 2, "z": 3 }

这不起作用:

extension obj1 {
   init(from decoder: Decoder) throws {
      //This is never called
   }

   func encode(to encoder: Encoder) throws {
      //This is never called
   }
}

幕后故事:

我正在将现有应用程序移植到iOS,并从C ++和Objective-C的混合物转换为Swift。此应用程序使用Metal来制作3D图形,因此广泛使用了矢量,矩阵,四元数等数学构造。

在项目开始时,我决定将Apple的simd库用于这些各种类型。我给了他们一个Typealias来匹配我们已经帮助移植的对象,并给扩展添加了一些未内置的功能。这一切都很好。

I'm now at the point where I need to be able to convert these types to/from JSON, and I've run into a problem. The simd structs already support Codable, but they use a different format than the one I need to support. Since simd uses structs, I can't derive from it and provide my own definition of init(from) and encode. It also appears as though I can't put my own definition in an extension either (the compiler doesn't complain but my versions aren't called either).

我目前使用结构包装器(即Vector3Codable)来完成此工作。但是,这意味着我具有这些simd成员的任何对象也必须提供自定义的Codable实现,而不是使用编译器添加的默认支持。

如果可能的话,我宁愿坚持使用simd,而不是为所有事情提供自己的实现。