In Objective-C the code looked liked this and worked flawlessly,
NSInteger random = arc4random_uniform(99) + 1
NSData *data = [NSData dataWithBytes:& random length: sizeof(random)];
int value = *(int*)([data bytes]);
How can this be done in Swift?
Data to interger thanks @rghome
In Swift 4:
There are a couple of things to consider when extracting an integer value from a
Data
stream. Signedness and Endianess. So I came up with a function in an extension toData
that infers Signedness from the type of integer you want to extract and passes Endianess andIndex
as parameters. The types of integers that can be extracted are all that conform toFixedWidthInteger
protocol.Reminder: This function will not check if the
Index
range is inside the bounds of theData
buffer so it may crash depending on the size of the type being extracted in relation to the end of the buffer.Example:
Results:
number1 is 8191
number2 is 65311
number3 is -225
number4 is 8191
Observe the function calls to see how the type to be extracted is inferred. Of course Endianess doesn't make sense for
Int8
orUInt8
, but the function works as expected.Values can later be cast to
Int
if needed.You might find this method useful if you are doing it a lot:
The function takes as a parameter the start position in the data to read the numeric type and it returns a value of the a type inferred from whatever you are assigning it to.
For example:
reads an 4 byte integer from position 10 in the data.
If you change
UInt32
toUInt16
it will read two bytes.Like this:
For Swift 3, you can do this (little endian, but similar for big):
You can modify this, add generics, etc. to fit other primitive types (and vary it depending on the endianness of the data bytes).
My contribution with a swift 3.1 extension :
Just call .int to get your value, just like this :