在 Swift 中将整数转换为 NSData [英] Converting an Integer to NSData in Swift

查看:85
本文介绍了在 Swift 中将整数转换为 NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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)

您可以在 将 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆