Question: How to convert Data to Int in Swift 3?

Question

How to convert Data to Int in Swift 3?

Answers 1
Added at 2016-12-26 23:12
Tags
Question

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

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

Then I updated syntax/naming due to 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?

Answers
nr: #1 dodano: 2016-12-26 23:12

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
Source Show
◀ Wstecz