如何更新 Swift 3 的 UnsafePointer 数据声明?
How do I update a statement of Data of UnsafePointer for Swift 3?
我收到以下关于此语句的错误:
let data = Data(bytes: UnsafePointer<UInt8>(cubeData), count: cubeData.count * MemoryLayout<Float>.size)
cubeData 定义为:var cubeData = [Float](repeating: 0, count: size * size * size * 4)
错误:
'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.
我该如何解决这个问题?
谢谢!
您可以使用 Array.withUnsafeBufferPointer
to obtain a buffer pointer (i.e. a pointer to an array with its length). Then use Data.init(buffer:)
从缓冲区指针启动数据。
let cubeData: [Float] = [1.1, 2.2, 3.3, 4.4]
let b = cubeData.withUnsafeBufferPointer { Data(buffer: [=10=]) }
print(b as NSData)
// <cdcc8c3f cdcc0c40 33335340 cdcc8c40>
我收到以下关于此语句的错误:
let data = Data(bytes: UnsafePointer<UInt8>(cubeData), count: cubeData.count * MemoryLayout<Float>.size)
cubeData 定义为:var cubeData = [Float](repeating: 0, count: size * size * size * 4)
错误:
'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.
我该如何解决这个问题?
谢谢!
您可以使用 Array.withUnsafeBufferPointer
to obtain a buffer pointer (i.e. a pointer to an array with its length). Then use Data.init(buffer:)
从缓冲区指针启动数据。
let cubeData: [Float] = [1.1, 2.2, 3.3, 4.4]
let b = cubeData.withUnsafeBufferPointer { Data(buffer: [=10=]) }
print(b as NSData)
// <cdcc8c3f cdcc0c40 33335340 cdcc8c40>