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?
As a result of all this, Swift will refuse to automatically convert between its various numeric types – you can't add an Int and a Double , you can't multiply a Float and an Int , and so on.
Swift 4.2+ String to Double You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.
Types that conform to the Equatable protocol can be compared for equality using the equal-to operator ( == ) or inequality using the not-equal-to operator ( != ). Most basic types in the Swift standard library conform to Equatable .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With