I\'m trying to create an NSData var from an array of bytes.
In Obj-C I might have done this:
NSData *endMarker = [[NSData al
For Swift 5 I have created another Data extension that works well.
extension Data {
init(fromArray values: [T]) {
var values = values
self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count))
}
func toArray(type: T.Type) -> [T] {
let value = self.withUnsafeBytes {
$0.baseAddress?.assumingMemoryBound(to: T.self)
}
return [T](UnsafeBufferPointer(start: value, count: self.count / MemoryLayout.stride))
}
}
Sample Usage
let data = Data(fromArray: [1, 2, 3, 4, 5])
let array = data.toArray(type: Int.self)
print(array)
// [1, 2, 3, 4, 5]