一个简单的 Encoder
和 Decoder
,可以将 Codable
Swift 类型序列化为扁平的、无标签的二进制表示形式。 请注意,这通常需要结构体具有固定大小。
struct Point: Codable {
let x: UInt16
let y: UInt16
}
let encoder = BinaryEncoder()
try encoder.encode(Point(x: 2, y: 3))
// -> Data([0, 2, 0, 3])
let decoder = BinaryDecoder()
try decoder.decode(Point.self, from: Data([0, 2, 0, 3]))
// -> Point(x: 2, y: 3)