在swift3中使用字节

在swift3中使用字节,swift,unsafe-pointers,Swift,Unsafe Pointers,“字节”不可用:请改用withUnsafeBytes 但我不知道如何使用它 float *vertexBuffer = (float *)positionSource.data.bytes; \uux=positionSource?.data.withUnsafeBytes({()->ResultType in }) withUnsafeBytes是一种通用方法,可以推断出内容类型 从闭包的类型。与 _ = positionSource?.data.withUnsafeBytes({ (<

“字节”不可用:请改用withUnsafeBytes

但我不知道如何使用它

float *vertexBuffer = (float *)positionSource.data.bytes;
\uux=positionSource?.data.withUnsafeBytes({()->ResultType in
})

withUnsafeBytes
是一种通用方法,可以推断出
内容类型
从闭包的类型。与

_ = positionSource?.data.withUnsafeBytes({ (<#UnsafePointer<ContentType>#>) -> ResultType in

   })
data.withUnsafeBytes{(vertexBuffer:UnsafePointer)位于
//使用vertexBuffer。。。
}
您将得到一个指向数据中字节的
UnsafePointer
。 请注意,此指针不能在闭包外部使用

您还可以计算一个结果并将其从闭包传回 给打电话的人。例如:

data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) in
    // Use  vertexBuffer ...
}
let result=data.withUnsafeBytes{(vertexBuffer:UnsafePointer)->浮点输入
让结果=/…计算结果。。。
返回结果
}

我想你可以这样做

let result = data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) -> Float in
    let result = // ... compute result ...
    return result
}
let str=“你好”
让strData=str.data(使用:String.Encoding.utf8)!
strData.withUnsafeBytes{(字节:UnsafePointer)->中的Void
打印(“\(字节[1])”//exp:access作为c字符串
}

希望能帮助你

哪种类型是
positionSource
及其内容是什么?
让positionSource=sphereNode.geometry?.getGeometrySources(for:.vertex)[0]
如果我想在闭包之外使用vertexBuffer,该怎么办?我想保持代码干净。@JohnAstion:
数据
仅在闭包环境中提供对其字节的访问。你关心的“清洁”是什么?明白了,谢谢!
let str = "hello"
let strData = str.data(using: String.Encoding.utf8)!
strData.withUnsafeBytes { (bytes: UnsafePointer<CChar>) -> Void in
          print("\(bytes[1])")  //exp: access as c string
}