Swift 3倾向于使用 Data
而不是 [UInt8]
,我试图找出最有效的/惯用的方法来将不同的数字类型(UInt8、 Double、 Float、 Int64等)作为 Data 对象进行编码/解码。
有 使用[ UInt8]的答案,但它似乎使用各种指针 API,我无法在数据上找到。
我想基本上一些自定义扩展,看起来像:
let input = 42.13 // implicit Double
let bytes = input.data
let roundtrip = bytes.to(Double) // --> 42.13
我查看了一大堆文档,真正困扰我的是如何获得某种类型的指针(OpaquePointer 或 BufferPointer 或 UnsafePointer?)从任何基本的结构(所有的数字都是)。在 C 中,我会在它前面加一个 & 符号,就是这样。