6

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?

Artem Stepanenko
  • 3,423
  • 6
  • 29
  • 51
  • 1
    Note that copying raw data into an int is fragile. If you try to exchange values between platforms with different "endian-ness" you will get the wrong result. iOS devices, Macs, and Windows PCs are all little-endian, but other hardware is big-endian. – Duncan C Dec 26 '16 at 22:48
  • 2
    Have a look at [round trip Swift number types to/from Data](http://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data). – Martin R Dec 26 '16 at 23:04
  • Thanks guys. I'll pay attention to your points. – Artem Stepanenko Dec 26 '16 at 23:34

1 Answers1

5

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
l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • 1
    Thanks for the fast answer. I've tried this, it gives a compile error `'getBytes(_:length:)' has been renamed to 'copyBytes(to:count:)'`. In the same time it works in a playground. Strange. – Artem Stepanenko Dec 26 '16 at 22:22
  • Yes that is strange; which version of Xcode are you using? I'm on 8.2 and it compiles without issue. I did notice that when I copied my code I used `NSInteger` instead of `Int`, but doubtful that has an effect. – l'L'l Dec 26 '16 at 22:38
  • Mine is 8.1. Does it work for you in a project? – Artem Stepanenko Dec 26 '16 at 22:42
  • Yep, works in a project and a playground both... – l'L'l Dec 26 '16 at 22:43
  • Cool, I'll update and let you know. Thanks a lot. – Artem Stepanenko Dec 26 '16 at 22:46
  • @ArtemStepanenko: I was able to reproduce the issue you have. Are you calling `NSData` or just `Data`? This is where things change... It appears that specifically using `NSData` there doesn't seem to have the issue, however, `Data` only allows `UInt8` and exhibits the same behavior as in your question. – l'L'l Dec 27 '16 at 00:22
  • Use `Data` and not `NSData` – lucgian841 May 29 '20 at 15:22