Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can encode array of CGPoint in Swift

Hello I found nice solution without array from here works OK

@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"}

Please I would like the similar solution with array, If anybody know please help me. I would like somethlig like:

@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"}
like image 696
Baldo Avatar asked Sep 01 '25 04:09

Baldo


1 Answers

You're going off of antiquated information. [CGPoint] is Codable without any extensions now.

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

If you actually need a wrapper, please post the code that requires it. Your question suggests that you don't need a wrapper.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!