How to extend float3 or any other built-in type to conform to the Codable protocol?

前端 未结 3 891
感动是毒
感动是毒 2021-01-18 15:14

In trying to serialize an array of float3 objects with the basic JSONEncoder, it\'s revealed that float3 does not conform to the Codable protocol, so this cannot be done.

3条回答
  •  无人共我
    2021-01-18 16:08

    I think that it is worth mentioning that you can simply use an unkeyed container to encode/decode your float3 properties as an array:

    extension float3: Codable {
        public init(from decoder: Decoder) throws {
            var container = try decoder.unkeyedContainer()
            try self.init(container.decode([Float].self))
        }
        public func encode(to encoder: Encoder) throws {
            var container = encoder.unkeyedContainer()
            try container.encode([x,y,z])
        }
    }
    

提交回复
热议问题