Reading Data into a Struct in Swift

前端 未结 3 1878
忘掉有多难
忘掉有多难 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:18

    Following on Leo Dabus answer, I created a slightly more readable constructor:

    extension Data {
        func object(at index: Index) -> T {
            subdata(in: index ..< index.advanced(by: MemoryLayout.size))
                .withUnsafeBytes { $0.load(as: T.self) }
        }
    }
    

    struct XPLBeacon {
        var majorVersion: UInt8
        var minorVersion: UInt8
        var applicationHostId: UInt32
        var versionNumber: UInt32
    
        init(data: Data) {
            var index = data.startIndex
            majorVersion = data.object(at: index)
    
            index += MemoryLayout.size(ofValue: majorVersion)
            minorVersion = data.object(at: index)
    
            index += MemoryLayout.size(ofValue: minorVersion)
            applicationHostId = data.object(at: index)
    
            index += MemoryLayout.size(ofValue: applicationHostId)
            versionNumber = data.object(at: index)
        }
    }
    

    What is not part of this is of course the checking for the correctness of the data. As other mentioned in comments, this could be done either by having a failable init method or by throwing an Error.

提交回复
热议问题