Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Int into NSData in Swift?

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?

like image 947
Cesare Avatar asked Feb 23 '15 18:02

Cesare


People also ask

How do I assign an Int to a string in Swift?

To convert an Int value to a String value in Swift, use String(). String() accepts integer as argument and returns a String value created using the given integer value.

What is an integer in Swift?

Swift provides an additional integer type, Int , which has the same size as the current platform's native word size: On a 32-bit platform, Int is the same size as Int32 . On a 64-bit platform, Int is the same size as Int64 .

What is data in Swift?

Data in Swift 3 is a struct that conforms to collection protocol. It is a collection of bytes ( [UInt8] array of unsigned integer 8 bits 0-255). – Leo Dabus.


1 Answers

With Swift 3.x to 5.0:

var myInt = 77 var myIntData = Data(bytes: &myInt,                       count: MemoryLayout.size(ofValue: myInt)) 
like image 102
Raphael Avatar answered Oct 08 '22 13:10

Raphael