在 Objective-C 中,代码看起来像这样,
In Objective-C the code looked liked this,
NSInteger random = arc4random_uniform(99) + 1 NSData *data = [NSData dataWithBytes:& random length: sizeof(random)];但是当我尝试在 Swift 中执行此操作时,
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)它给了我一个错误,NSInteger 不能转换为 @lvalue inout $T1
It gives me an error staying that "NSInteger is not convertible to @lvalue inout $T1
任何帮助将不胜感激!
推荐答案当你要以这种方式将一个指向变量的指针作为参数发送时,该变量需要是可变的(即用 var),因为接收函数或方法将能够直接修改变量.你想要的代码是:
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)您可以在 UnsafePointer 的更多信息.html#//apple_ref/doc/uid/TP40014216-CH8-XID_14">将 Swift 与 Cocoa 和 Objective-C 结合使用:与 C API 交互.
You can read more about using UnsafePointer<Void> in Using Swift with Cocoa and Objective-C: Interacting with C APIs.
更多推荐
在 Swift 中将整数转换为 NSData
发布评论