Swift3 将nsuid转换为UnsafePointer<;UInt8>;

Swift3 将nsuid转换为UnsafePointer<;UInt8>;,swift3,uuid,unsafe-pointers,nsuuid,Swift3,Uuid,Unsafe Pointers,Nsuuid,更新到Swift 3后,UUID对象上似乎既没有getUUIDBytes也没有getBytes let uuid = UIDevice.current.identifierForVendor let mutableUUIDData = NSMutableData(length:16) uuid.getBytes(UnsafeMutablePointer(mutableUUIDData!.mutableBytes)) // ^^^ compiler error, value of type U

更新到Swift 3后,
UUID
对象上似乎既没有
getUUIDBytes
也没有
getBytes

let uuid = UIDevice.current.identifierForVendor
let mutableUUIDData = NSMutableData(length:16)
uuid.getBytes(UnsafeMutablePointer(mutableUUIDData!.mutableBytes))
//   ^^^ compiler error, value of type UUID? has no member getBytes
即使文档中将
getBytes
列为UUID上的方法,我也会遇到此错误:

一种正确的方法:

let uuid = UIDevice.current.identifierForVendor!
var rawUuid = uuid.uuid

withUnsafePointer(to: &rawUuid) {rawUuidPtr in //<- `rawUuidPtr` is of type `UnsafePointer<uuid_t>`.
    rawUuidPtr.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {bytes in
        //Use `bytes` only in this closure. (Do NEVER export `bytes` out of the closure.)
        print(bytes[0],bytes[1])
        //...
    }
}
withUnsafePointer(to: &rawUuid) {rawUuidPtr in //<- `rawUuidPtr` is of type `UnsafePointer<uuid_t>`.
    let bytes = UnsafeRawPointer(rawUuidPtr).assumingMemoryBound(to: UInt8.self)
    //Use `bytes` only in this closure. (Do NEVER export `bytes` out of the closure.)
    print(bytes[0],bytes[1])
    //...
}

你的想法太复杂了:

func getUUID ( ) -> Data {
    let uuid = NSUUID()
    var bytes = [UInt8](repeating: 0, count: 16)
    uuid.getBytes(&bytes)
    return Data(bytes: bytes)
}
为什么会这样

假设你有:

func printInt(atAddress p: UnsafeMutablePointer<Int>) {
    print(p.pointee)
}
但你也可以这样做:

var numbers = [5, 10, 15, 20]
printInt(atAddress: &numbers)
// Prints "5"
这是一种“隐式桥接”。引自:

隐式创建指向数组元素的可变指针 使用inout语法传递数组时

在当前函数返回之前,此隐式桥接仅保证有效指针。这样的指针决不能“转义”当前函数上下文,但将它们用作inout参数始终是安全的,因为inout参数始终只能保证在被调用函数返回之前有效,而被调用函数必须在当前函数返回之前有效,所以这不会出错

对于那些不知道的人,将
UUID
转换为
nsuid
…作为nsuid
),反之(
…作为UUID
)保证总是成功的。但如果您坚持使用
UUID
,最简单的方法是:

private
func getUUID ( ) -> Data {
    var uuid = UUID().uuid
    return withUnsafePointer(to: &uuid) {
        return Data(bytes: $0, count: MemoryLayout.size(ofValue: uuid))
    }
}

我想获得您的输入,我有3个
数据
变量,它们的
字节
我需要按顺序传递到
SHA1\u Update
。建议的流是否真的有3个嵌套的
块,其中包含unsafebytes
?@ray,在Swift 3中处理
数据时,这似乎是正确的方法。或者您可以使用
不安全的[Mutable]指针
。有人(苹果开发论坛的苹果员工)建议用C/Objective-C编写一个更快速的包装器。
var numbers = [5, 10, 15, 20]
printInt(atAddress: &numbers)
// Prints "5"
private
func getUUID ( ) -> Data {
    var uuid = UUID().uuid
    return withUnsafePointer(to: &uuid) {
        return Data(bytes: $0, count: MemoryLayout.size(ofValue: uuid))
    }
}