使用未解析的标识符 'sizeof'

Use of unresolved identifier 'sizeof'

我正在尝试在两个设备之间发送一个位置,所以我需要将该位置转换为 NSData。我在网上找到了一些东西,但出现错误:使用未解析的标识符 'sizeof'。我不知道如何解决,你能帮我吗?这是我的代码:

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 {
    }

首先,error 变量毫无意义。 try? 根本不影响 error

sizeof 已更改为 MemoryLayout.size(ofValue:。参数是 positionToSend,不是类型 CGPoint

CGPoint 创建 Data(不是 NSData)的 Swift 3+ 方法是

let dataSend = Data(bytes: &positionToSend, count: MemoryLayout.size(ofValue: positionToSend))

我会在 Swift 4 中将您的代码重写为:

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

你不需要withUnsafePointer