gpt4 book ai didi

swift - 如何在 Swift 中编码 CGPoint 数组

转载 作者:行者123 更新时间:2023-12-04 01:11:02 25 4
gpt4 key购买 nike

你好,我从 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"}

最佳答案

您将使用过时的信息。 [CGPoint] Codable 现在没有任何扩展。

struct Foo2: Encodable {
var pt: [CGPoint] = []
var other = "zxcv"
}

如果您确实需要包装器,请发布需要它的代码。您的问题表明您不需要包装器。

关于swift - 如何在 Swift 中编码 CGPoint 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64843460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com