swift 2 -> swift 3

data.bytes
<pre><code>
extension Data {
<p>
init<T>(fromArray values: [T]) {
<p>
var values = values self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count))
<p> }
<p>
func toArray<T>(type: T.Type) -> [T] {
<p>
return self.withUnsafeBytes {
<p>
[T] (UnsafeBufferPointer(start: $0, count: self.count/sizeof(T)))
<p> }
<p> }
<p>}
</pre></code>
<pre><code>
Example:
<p>let input: [Int16] = [1, Int16.max, Int16.min]
<p>let data = Data(fromArray: input)print(data) // <0100ff7f 0080>
<p>let roundtrip = data.toArray(type: Int16.self)print(roundtrip) // [1, 32767, -32768]
</pre></code>

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

data.getBytes
<pre><code>
For NSData:
<p>var values = [UInt8] (repeating:0, count:data!.length)data.getBytes(&values, length: data!.length)
<p>
<p>
For Data:
<p>var values = [UInt8] (repeating:0, count:data!.count)data.copyBytes(to: &values, count: data!.count)
</pre></code>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容