在 Swift 中将整数转换为 NSData

编程入门 行业动态 更新时间:2024-10-25 00:25:48
本文介绍了在 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)

您可以在 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

本文发布于:2023-10-24 16:52:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524487.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   转换为   中将   Swift   NSData

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!