【问题标题】:Converting an Integer to NSData in Swift在 Swift 中将整数转换为 NSData
【发布时间】:2014-10-07 00:58:22
【问题描述】:

在 Objective-C 中,代码看起来像这样,

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

但是当我尝试在 Swift 中执行此操作时,

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

它给了我一个错误提示“NSInteger 不能转换为@lvalue inout $T1

任何帮助将不胜感激!

【问题讨论】:

  • 您实际上是在哪一行得到的?第一个对我来说有点奇怪(尽管我还没有在 Swift 中做太多事情)。试试Int 而不是NSInteger
  • 感谢您的回复。在 Swift 中声明数据变量时出现错误。 Objective-C 的方式确实很时髦,但很有效!
  • 顺便说一句 sizeof(random) 可以是 4 或 8 但绝不是 3

标签: ios swift nsdata


【解决方案1】:

当你要以这种方式发送一个指向变量的指针作为参数时,该变量需要是可变的(即用var声明),因为接收函数或方法将能够直接修改变量。你想要的代码是:

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

您可以在Using Swift with Cocoa and Objective-C: Interacting with C APIs 中阅读有关使用UnsafePointer<Void> 的更多信息。

【讨论】:

  • length: 3 看起来很可疑 :)
  • 非常可疑
猜你喜欢
  • 2014-12-01
  • 2015-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
相关资源
最近更新 更多