如何在Swift 3中将数据转换为Int?

Art*_*nko 6 ios swift swift2 swift3

有很多来源解释如何在Swift 2中制作它作为基础:

var value: Int = 0
let data: NSData = ...;
data.getBytes(&value, length: sizeof(Int))
Run Code Online (Sandbox Code Playgroud)

然后我更新了Swift 3的语法/命名:

var value: Int = 0
let data: NSData = ...;
data.copyBytes(to: &value, count: MemoryLayout<Int>.size)
Run Code Online (Sandbox Code Playgroud)

然而它不起作用.编译器不喜欢它的类型value,它应该是UInt8.但我想要Int.谁知道我怎么能做到这一点?

l'L*_*L'l 6

也许尝试这样:

var src: Int = 12345678
var num: Int = 0 // initialize

let data = NSData(bytes: &src, length: MemoryLayout<Int>.size)
data.getBytes(&num, length: MemoryLayout<Int>.size)
print(num) // 12345678
Run Code Online (Sandbox Code Playgroud)