如何在Swift 3中将数据转换为Int? [重复]

时间:2022-09-06 16:31:57

This question already has an answer here:

这个问题在这里已有答案:

There're a lot of sources explaining how to make it in Swift 2 which I took as a base:

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

var value: Int = 0
let data: NSData = ...;
data.getBytes(&value, length: sizeof(Int))

Then I updated syntax/naming due to Swift 3:

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

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

Nevertheless it doesn't work. The compiler doesn't like the type of value, it says it should be UInt8. But I want Int. Anybody knows how can I achieve this?

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

1 个解决方案

#1


6  

Maybe try like this:

也许尝试这样:

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

#1


6  

Maybe try like this:

也许尝试这样:

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