Swift 3.0 从数据中检索 int
Swift 3.0 retrieving int from Data
代码如下:
func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer){
if(gameOver){
return;
}
if(variables.background){
match.disconnect()
}
if(!randReceived){
levelLabel.text = "Match Against "+(match.players[0] ).displayName!
self.addChild(levelLabel)
randReceived=true
var number: Int = 0
number = data.withUnsafeBytes {
(pointer: UnsafePointer<Int>) -> Int in
return pointer.pointee
}
}
}
它给出了一个错误 "Value of type Data has no member 'withUnsafeBytes'"。我该如何解决这个问题?
您的代码有效。我在 playground 中尝试了 essential 部分没有任何问题:
var test: Int = 1000
let data = Data(bytes: &test, count: MemoryLayout<Int>.size)
var number: Int = 0
number = data.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int in
return pointer.pointee
}
在你的情况下,错误是:
Value of type Data has no member 'withUnsafeBytes
基本上这样的错误表明它无法在 Data
对象上找到该特定函数。
您可能已将自己的 Data
定义为覆盖了 Foundation
.
中定义的 Data
结构的 class/struct/something
Option-Click 并确认它说:
Declared in Foundation
请试试这个,它会帮助你
extension Data {
func copyBytes<T>(as _: T.Type) -> [T] {
return withUnsafeBytes { (bytes: UnsafePointer<T>) in
Array(UnsafeBufferPointer(start: bytes, count: count / MemoryLayout<T>.stride))
}
}
}
或者
let size = MemoryLayout<Int16>.stride
let data = Data(bytes: [1, 0, 2, 0, 3, 0]) // little endian for 16-bit values
let int16s = data.withUnsafeBytes { (bytes: UnsafePointer<Int16>) in
Array(UnsafeBufferPointer(start: bytes, count: data.count / size))
}
代码如下:
func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer){
if(gameOver){
return;
}
if(variables.background){
match.disconnect()
}
if(!randReceived){
levelLabel.text = "Match Against "+(match.players[0] ).displayName!
self.addChild(levelLabel)
randReceived=true
var number: Int = 0
number = data.withUnsafeBytes {
(pointer: UnsafePointer<Int>) -> Int in
return pointer.pointee
}
}
}
它给出了一个错误 "Value of type Data has no member 'withUnsafeBytes'"。我该如何解决这个问题?
您的代码有效。我在 playground 中尝试了 essential 部分没有任何问题:
var test: Int = 1000
let data = Data(bytes: &test, count: MemoryLayout<Int>.size)
var number: Int = 0
number = data.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int in
return pointer.pointee
}
在你的情况下,错误是:
Value of type Data has no member 'withUnsafeBytes
基本上这样的错误表明它无法在 Data
对象上找到该特定函数。
您可能已将自己的 Data
定义为覆盖了 Foundation
.
Data
结构的 class/struct/something
Option-Click 并确认它说:
Declared in Foundation
请试试这个,它会帮助你
extension Data {
func copyBytes<T>(as _: T.Type) -> [T] {
return withUnsafeBytes { (bytes: UnsafePointer<T>) in
Array(UnsafeBufferPointer(start: bytes, count: count / MemoryLayout<T>.stride))
}
}
}
或者
let size = MemoryLayout<Int16>.stride
let data = Data(bytes: [1, 0, 2, 0, 3, 0]) // little endian for 16-bit values
let int16s = data.withUnsafeBytes { (bytes: UnsafePointer<Int16>) in
Array(UnsafeBufferPointer(start: bytes, count: data.count / size))
}