Search code examples
swiftswift3unsafe-pointers

How do I update a statement of Data of UnsafePointer for Swift 3?


I'm getting the error below for this statement:

 let data = Data(bytes: UnsafePointer<UInt8>(cubeData), count: cubeData.count * MemoryLayout<Float>.size)

cubeData is defined as: var cubeData = [Float](repeating: 0, count: size * size * size * 4)

Error:

 'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

How can I fix this?

Thanks!


Solution

  • You could use Array.withUnsafeBufferPointer to obtain a buffer pointer (i.e. a pointer to an array with its length). Then use Data.init(buffer:) to initiate the data from a buffer pointer.

    let cubeData: [Float] = [1.1, 2.2, 3.3, 4.4]
    
    let b = cubeData.withUnsafeBufferPointer { Data(buffer: $0) }
    
    print(b as NSData)
    // <cdcc8c3f cdcc0c40 33335340 cdcc8c40>