Reading Data into a Struct in Swift

前端 未结 3 1880
忘掉有多难
忘掉有多难 2020-12-06 07:46

I\'m trying to read bare Data into a Swift 4 struct using the withUnsafeBytes method. The problem

The network UDP packet has t

3条回答
  •  隐瞒了意图╮
    2020-12-06 08:38

    Since Swift 3 Data conforms to RandomAccessCollection, MutableCollection, RangeReplaceableCollection. So you can simply create a custom initializer to initialise your struct properties as follow:

    struct XPLBeacon {
        let majorVersion, minorVersion: UInt8             // 1 + 1 = 2 Bytes
        let applicationHostId, versionNumber: UInt32      // 4 + 4 = 8 Bytes
        init(data: Data) {
            self.majorVersion = data[0]
            self.minorVersion = data[1]
            self.applicationHostId = data
                .subdata(in: 2..<6)
                .withUnsafeBytes { $0.load(as: UInt32.self) }
            self.versionNumber = data
                .subdata(in: 6..<10)
                .withUnsafeBytes { $0.load(as: UInt32.self) }
        }
    }
    

    var data = Data([0x01,0x02, 0x0A, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00,0x00])
    print(data as NSData)     // "{length = 10, bytes = 0x01020a0000000b000000}\n" <01020a00 00000b00 0000>
    
    let beacon = XPLBeacon(data: data)
    beacon.majorVersion       // 1
    beacon.minorVersion       // 2
    beacon.applicationHostId  // 10
    beacon.versionNumber      // 11
    

提交回复
热议问题