如何在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))
}