Extract struct from NSData in Swift

I’m making Game Center game. I send a data packet containing a struct MovePacket like this:

var packet = MovePacket(packetID: 1, move: myMove)

let dataPacket = NSData(bytes: &packet, length: sizeof(MovePacket))

currentMatch!.sendDataToAllPlayers(dataPacket, withDataMode: GKMatchSendDataMode.Reliable, error: nil)

This works like in Objective-C, but I don’t understand how to decode the received NSData back to my struct MovePacket. This is one of my tries:

  • Sorting array(NSString + Number) using NSSortDescriptor in IOS?
  • Auto Layout with relative constraints not affecting systemLayoutSizeFittingSize: for UITableViewCell
  • Can you test replaykit in the simulator in Xcode?
  • Saving SecKeyRef device generated public/private key pair on disk
  • Shadow effects on ImageView in iOS
  • Passing array through segue in swift
  • func match(match: GKMatch!, didReceiveData data: NSData!, fromRemotePlayer player: GKPlayer!) {
    
        var packet : MovePacket 
    
        data.getBytes(&packet, length: sizeof(MovePacket)) // getting error here: Address of variable 'packet' taken before it is initialized
    
        println(packet) //Variable 'packet' used before being initialized
    
    }
    

    Solutions Collect From Internet About “Extract struct from NSData in Swift”

    Assuming you meant “decode it back from NSData”:

    func match(match: GKMatch!, didReceiveData data: NSData!, fromRemotePlayer player: GKPlayer!) {
        if data.length == sizeof(MovePacket) {
            let packet = UnsafePointer<MovePacket>(data.bytes).memory
            println(packet)
        } else {
            // error: data size is incorrect
        }
    }