在Swift 3中从UUID获取数据 [英] Get Data from UUID in Swift 3

查看:247
本文介绍了在Swift 3中从UUID获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下用Objective C编写的代码,试图在Swift 3中工作.某些功能在Swift 3中似乎不可用.这是Objective C中的代码

I have the following code written in Objective C that I am trying to get working in Swift 3. Some of the functions equivalents do not appear to be available in Swift 3. Here is the code is the code in Objective C

NSUUID *vendorIdentifier = [[UIDevice currentDevice] identifierForVendor];
uuid_t uuid;
[vendorIdentifier getUUIDBytes:uuid];
NSData *vendorData = [NSData dataWithBytes:uuid length:16];

以及我目前在Swift 3中的工作,该版本可以编译并运行,但未给出正确的答案.

and my current effort in Swift 3 which compiles and runs but is not giving the correct answer.

let uuid = UIDevice.current.identifierForVendor?.uuidString
let uuidData = uuid?.data(using: .utf8)
let uuidBytes = uuidData?.withUnsafeBytes { UnsafePointer<UInt8>($0) }
let vendorData : NSData  = NSData.init(bytes: uuidBytes, length: 16)
let hashData = NSMutableData()
hashData.append(vendorData as Data)

推荐答案

UUIDuuid属性是一个C数组,导入到Swift 作为一个元组.利用Swift保留内存布局的事实 导入的C结构,您可以将指针传递给元组 到Data(bytes:, count:)构造函数:

The uuid property of UUID is a C array with is imported to Swift as a tuple. Using the fact that Swift preserves the memory layout of imported C structures, you can pass a pointer to the tuple to the Data(bytes:, count:) constructor:

if let vendorIdentifier = UIDevice.current.identifierForVendor {
    var uuid = vendorIdentifier.uuid
    let data = withUnsafePointer(to: &uuid) {
        Data(bytes: $0, count: MemoryLayout.size(ofValue: uuid))
    }

    // ...
}

Swift 4.2(Xcode 10)开始,您无需进行可变 首先复制:

As of Swift 4.2 (Xcode 10) your don't need to make a mutable copy first:

if let vendorIdentifier = UIDevice.current.identifierForVendor {
    let data = withUnsafePointer(to: vendorIdentifier.uuid) {
        Data(bytes: $0, count: MemoryLayout.size(ofValue: vendorIdentifier.uuid))
    }

    // ...
}

这篇关于在Swift 3中从UUID获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆