如何在Swift中将Int转换为NSData?

问题描述 投票:16回答:3

在Objective-C中,我使用以下代码

  1. Int变量转换为NSData,即一个字节包。 int myScore = 0; NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
  2. 将转换后的NSData变量用于方法。 [match sendDataToAllPlayers: packet withDataMode: GKMatchSendDataUnreliable error: &error];

我尝试将Objective-C代码转换为Swift:

var myScore : Int = 0

func sendDataToAllPlayers(packet: Int!,
            withDataMode mode: GKMatchSendDataMode,
            error: NSErrorPointer) -> Bool {

            return true
}

但是,我无法将Int变量转换为NSData并将其用作方法。我怎样才能做到这一点?

ios swift int nsdata
3个回答
41
投票

使用Swift 3.x到5.0:

var myInt = 77
var myIntData = Data(bytes: &myInt, 
                     count: MemoryLayout.size(ofValue: myInt))

23
投票

要将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))
}

3
投票

你可以这样转换:

var myScore: NSInteger = 0
let data = NSData(bytes: &myScore, length: sizeof(NSInteger))
© www.soinside.com 2019 - 2024. All rights reserved.