I am not sure where I got this piece of code. But here I have some code to get series of Vertex(or whatever) out of Data in swift.
struct Vertex {
var x, y, z, w: Float16
var r, g, b, a: Float16
}
extension Data {
func elements<T>() -> [T] {
return withUnsafeBytes {
Array(UnsafeBufferPointer<T>(start: $0, count: count/MemoryLayout<T>.stride))
}
}
}
It works fine to me, but I have this warning. I spent some time, but I cannot figure this out. So could someone please help me out?
'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
By the way, I am trying to save and load large number of data with this way with pairing of following piece of code.
extension Array {
var data: Data {
var value = self
return NSData(bytes: &value, length: MemoryLayout<Element>.stride * self.count) as Data
}
}
Thank you,
- EDIT
Here is the code what I like to do, it works fine, but I like to get rid of warning...
struct Vertex: Equatable {
var x, y, z, w: Float16
var r, g, b, a: Float16
// assumption: no precision error
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w &&
lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a
}
}
let v0 = Vertex(x: 1, y: 2, z: 3, w: 4, r: 0, g: 0.25, b: 0.5, a: 0.75)
let v1 = Vertex(x: 5, y: 6, z: 7, w: 8, r: 0.2, g: 0.4, b: 0.6, a: 0.8)
let v2 = Vertex(x: 9, y: 0, z: 1, w: 2, r: 0.5, g: 0.75, b: 0.0, a: 1.0)
let original: [Vertex] = [v0, v1, v2]
let data = original.data
print(data as NSData)
let restored: [Vertex] = data.elements()
let w0 = restored[0]
let w1 = restored[1]
let w2 = restored[2]
print(v0 == w0)
print(v1 == w1)
print(v2 == w2)