【发布时间】:2020-11-15 10:44:19
【问题描述】:
您好,我从 here 找到了没有数组的好解决方案,可以正常工作
@propertyWrapper
struct EncodablePoint: Encodable {
var wrappedValue: CGPoint
enum CodingKeys: CodingKey {
case x
case y
}
func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(wrappedValue.x, forKey: .x)
try c.encode(wrappedValue.y, forKey: .y)
}
}
//usage:
struct Foo: Encodable {
@EncodablePoint var pt: CGPoint = CGPoint(x: 123, y: 456)
var other = "zxcv"
}
let foo = Foo()
let encoded = try! JSONEncoder().encode(foo)
print(String(bytes: encoded, encoding: .utf8) ?? "nil") // {"pt":{"x":123,"y":456},"other":"zxcv"}
我想要类似的数组解决方案,如果有人知道请帮助我。 我想要一些类似的东西:
@propertyWrapper
struct EncodablePointsArray: Encodable {
var wrappedValue: [CGPoint]
enum CodingKeys: CodingKey {
?????
}
func encode(to encoder: Encoder) throws {
??????
}
}
struct Foo2: Encodable {
@EncodablePointsArray var pt: [CGPoint] = [CGPoint]
var other = "zxcv"
}
let foo2 = Foo2()
let encoded = try! JSONEncoder().encode(foo2)
print(String(bytes: encoded, encoding: .utf8) ?? "nil")
// I wold like output like : {"ArrayPoints“:[{„x“:1.1,“y“:1.2},{„x“:2.1,“y“:3.4}]},"other":"zxcv"}
【问题讨论】: