As Data are bytes [UInt8] (with capital I) and Data are interchangeable.
For [uint16_t] and [uint32_t] use MartinR's Data extension
extension Data {
init<T>(fromArray values: [T]) {
self = values.withUnsafeBytes { Data($0) }
}
func toArray<T>(type: T.Type) -> [T] where T: ExpressibleByIntegerLiteral {
var array = Array<T>(repeating: 0, count: self.count/MemoryLayout<T>.stride)
_ = array.withUnsafeMutableBytes { copyBytes(to: $0) }
return array
}
}
And an example, uint16Bytes represents an array of [UInt16] although the type is [UInt8]
let uint16Bytes : [UInt8] = [0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00]
let uint16Data = Data(uint16Bytes)
let array = uint16Data.toArray(type: UInt16.self).map(Int.init) // [1, 2, 3, 4]
toArray returns [UInt16]. You have to map the array to [Int]