简体   繁体   中英

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM