如何在Swift中将Int转换为NSData? [英] How to convert an Int into NSData in Swift?
本文介绍了如何在Swift中将Int转换为NSData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Objective-C中,我使用以下代码
In Objective-C I use the following code to
-
转换
Int
变量为NSData
,一个字节包。
Convert an
Int
variable intoNSData
, a packet of bytes.
int myScore = 0;
NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
使用转换后的 NSData
变量一个方法。
[match sendDataToAllPlayers:
packet withDataMode: GKMatchSendDataUnreliable
error: &error];
我尝试将Objective-C代码转换为Swift:
I tried converting the Objective-C code into Swift:
var myScore : Int = 0
func sendDataToAllPlayers(packet: Int!,
withDataMode mode: GKMatchSendDataMode,
error: NSErrorPointer) -> Bool {
return true
}
但是,我是无法将 Int
变量转换为 NSData
并将其用作方法。我怎么能这样做?
However, I am not able to convert an Int
variable into an NSData
and use it an a method. How can I do that?
推荐答案
将 Int
转换为 NSData
:
var score: Int = 1000
let data = NSData(bytes: &score, length: sizeof(Int))
var error: NSError?
if !match.sendDataToAllPlayers(data, withDataMode: .Unreliable, error: &error) {
println("error sending data: \(error)")
}
将其转换回来:
func match(match: GKMatch!, didReceiveData data: NSData!, fromPlayer playerID: String!) {
var score: Int = 0
data.getBytes(&score, length: sizeof(Int))
}
这篇关于如何在Swift中将Int转换为NSData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文