如何在swift3中使用Data初始化struct var

时间:2017-03-16 08:16:58

标签: swift3

我有这样的结构

struct Str{

let item1: UINT16
let item2: UINT16
let item3: UINT32

}

我有一个struct var mystr

var mystr = Str(item1: 0x0101, item2: 0xffff, item3: 4)

我将struct var存储到Data var

var myData = Data(bytes: &mystr, count:MemoryLayout<Str>.size)

我的问题是如何使用Data var初始化一个新的Str var(将数据的值存储到struct中)

由于

1 个答案:

答案 0 :(得分:1)

我还不足以告诉专家告诉将一些内存转储到Data对象然后使用该内存来初始化结构是多么危险,但这是你可以做的:

let strFromData = myData.withUnsafeBytes { (p: UnsafePointer<Str>) -> Str in
    return p.pointee
}

甚至更短:

let strFromData2 = myData.withUnsafeBytes { $0.pointee as Str }

我在以前的项目中所做的是逐个处理结构的成员:

extension Data
{
    mutating func append<T>(value: T)
    {
        var v = value
        self.append(UnsafeBufferPointer(start: &v, count: 1))
    }
}

var data = Data()
data.append(value: mystr.item1)
data.append(value: mystr.item2)
data.append(value: mystr.item3)

使用Str初始化程序从myData构建Str

let strFromData3 = myData.withUnsafeBytes { (p: UnsafePointer<UInt16>) -> Str in
    let item1 = p[0]
    let item2 = p[1]
    let p2 = UnsafeRawPointer(p).bindMemory(to: UInt32.self, capacity: 2)
    let item3 = p2[1]
    return Str(item1: item1, item2: item2, item3: item3)
}