How to convert an Int into NSData in Swift?

Cesare picture Cesare · Feb 23, 2015 · Viewed 28.5k times · Source

In Objective-C I use the following code to

  1. Convert an Int variable into NSData, a packet of bytes.

    int myScore = 0;
    NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
    
  2. Use the converted NSData variable into a method.

    [match sendDataToAllPlayers: 
    packet withDataMode: GKMatchSendDataUnreliable 
    error: &error];
    

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
}

However, I am not able to convert an Int variable into an NSData and use it an a method. How can I do that?

Answer

Raphael picture Raphael · Apr 6, 2017

With Swift 3.x to 5.0:

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