How to convert data to Int in Swift 3?

There are many sources explaining how to do this in Swift 2 , which I used as a base:

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

Then I updated the syntax / naming due to Swift 3 :

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

However, this does not work. The compiler does not like the type value; he says that it should be UInt8. But I want to Int. Does anyone know how I can achieve this?

+4
source share
1 answer

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
+4
source

Source: https://habr.com/ru/post/1664948/


All Articles