1

I'm trying to send a position between two devices, so I need to convert the position to NSData. I found something on the net but I have an error: Use of unresolved identifier 'sizeof'. I don't know how to solve, could you help me?. Here's my code:

var error: Error?
    var positionToSend = car.position
    let dataSend = NSData(bytes: &positionToSend, length: sizeof(CGPoint))
    try? match.sendData(toAllPlayers: dataSend, with: .unreliable)
    if error != nil {
    }
Andrea Culot
  • 114
  • 2
  • 9
  • For sizeof see [Swift: How to use sizeof?](https://stackoverflow.com/a/27640066/1187415). – Using the approach from [round trip Swift number types to/from Data](https://stackoverflow.com/q/38023838/1187415) it would be `let dataSend = Data(buffer: UnsafeBufferPointer(start: &positionToSend, count: 1))` – Martin R Jul 21 '18 at 17:01

2 Answers2

1

First of all the error variable is pointless. try? doesn't affect error at all.

sizeof has been changed to MemoryLayout.size(ofValue:. The argument is positionToSend, not the type CGPoint

The Swift 3+ way to create Data (not NSData) from a CGPoint is

let dataSend = Data(bytes: &positionToSend, count: MemoryLayout.size(ofValue: positionToSend))
vadian
  • 232,468
  • 27
  • 273
  • 287
1

I would rewrite your code in Swift 4 as:

var positionToSend = car.position
let dataSend = Data(bytes: &positionToSend, count: MemoryLayout.size(ofValue: positionToSend))
do {
    try match.sendData(toAllPlayers: dataSend, with: .unreliable)
} catch {
    //Write code for `if error != nil`...
    print(error)
}

You do not need withUnsafePointer.

OOPer
  • 44,179
  • 5
  • 90
  • 123