代码之家  ›  专栏  ›  技术社区  ›  Vyacheslav

无法使用getbytes将数据转换为int

  •  0
  • Vyacheslav  · 技术社区  · 6 年前
    let objectData: Data = .....
    var intValue: Int = 0
    objectData.getBytes(&intValue, length: MemoryLayout<Int>.size) // there is an error
    return intValue
    

    编译器说是

    与“int”类型的非inout参数一起使用的“&”

    发生了什么?

    编辑

    顺便说一句, NSData 工作正常

    var intValue: Int = 0
    (objectData as NSData).getBytes(&intValue, length: MemoryLayout<Int>.size)
    return intValue
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Martin R    6 年前

    Data 没有 getBytes() 方法。你可以搭桥去 NSData (就像你那样) 或使用 withUnsafeBytes() 方法

    let objectData = Data(bytes: [1, 2, 0, 0, 0, 0, 0, 0])
    let intValue: Int = objectData.withUnsafeBytes { $0.pointee }
    print(intValue) // 513
    

    (假设 objectData 至少包含8个字节)。

    在封口处, $0 是指向字节及其类型的指针 从上下文推断为 UnsafePointer<Int> .