Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Data to Int in Swift 3? [duplicate]

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?

like image 869
Artem Stepanenko Avatar asked Dec 26 '16 22:12

Artem Stepanenko


People also ask

Can you add double and Int in Swift?

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.

How do I convert a string to a double in Swift?

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.

What does != Mean in Swift?

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 .


1 Answers

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
like image 111
l'L'l Avatar answered Sep 30 '22 02:09

l'L'l