swift 2 -> swift 3

1225 ワード

data.bytes

extension Data {


init(fromArray values: [T]) {


var values = values self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count))

}


func toArray(type: T.Type) -> [T] {


return self.withUnsafeBytes {


[T] (UnsafeBufferPointer(start: $0, count: self.count/sizeof(T)))

}

}

}


Example:

let input: [Int16] = [1, Int16.max, Int16.min]

let data = Data(fromArray: input)print(data) // <0100ff7f 0080>

let roundtrip = data.toArray(type: Int16.self)print(roundtrip) // [1, 32767, -32768]


http://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data
data.getBytes

For NSData:

var values = [UInt8] (repeating:0, count:data!.length)data.getBytes(&values, length: data!.length)



For Data:

var values = [UInt8] (repeating:0, count:data!.count)data.copyBytes(to: &values, count: data!.count)