How to get data from [Float] correctly?

I need to retrieve the Data from [Float] in order to do it I use such an approach

var vertexData: [Float] = [...]

let p_vertexData: Data = Data(buffer: UnsafeBufferPointer(start: vertexData, count: VDataCount))

and it works well except for the annoying warning that I get

Initialization of 'UnsafeBufferPointer' results in a dangling buffer pointer

so, I changed it to the recommended approach

let p_vertexData: Data = withUnsafeBytes(of: vertexData) { Data($0) }

But this way it doesn't work well, I don't know what exactly is going on, but the result (where I use the Data) is not what is expected.

The question is - how to get the Data in a proper way?

Answered by OOPer in 700646022

I would write it like this:

let p_vertexData = vertexData.withUnsafeBufferPointer {bufPtr in
    Data(buffer: bufPtr)
}

Try this:

let vertexData: [Float] = [1, 2, 3]

var data = Data()
vertexData.withUnsafeBytes {
    data.append(contentsOf: $0)
}
Accepted Answer

I would write it like this:

let p_vertexData = vertexData.withUnsafeBufferPointer {bufPtr in
    Data(buffer: bufPtr)
}
How to get data from [Float] correctly?
 
 
Q