Converting an Integer to NSData in Swift

大憨熊 提交于 2019-12-10 17:31:25

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/26227066/converting-an-integer-to-nsdata-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!