Search code examples
iosswiftnsdata

Converting an Integer to NSData in Swift


In Objective-C the code looked liked this,

    NSInteger random = arc4random_uniform(99) + 1 
    NSData *data = [NSData dataWithBytes:& random length: sizeof(random)];

But when I try to do this in Swift,

    let random:NSInteger = NSInteger(arc4random_uniform(99) + 1) //(1-100)
    let data = NSData(bytes: &random, length: 3)

It gives me an error staying that "NSInteger is not convertible to @lvalue inout $T1

Any help would be greatly appreciated!


Solution

  • When you're going to send a pointer to a variable as a parameter in this way, the variable needs to be mutable (that is, declared with var), since the receiving function or method will be able to directly modify the variable. The code you want is:

    var random = NSInteger(arc4random_uniform(99) + 1) //(1-100)
    let data = NSData(bytes: &random, length: 3)
    

    You can read more about using UnsafePointer<Void> in Using Swift with Cocoa and Objective-C: Interacting with C APIs.