从 Swift 中的 UUID 获取数据 3

Get Data from UUID in Swift 3

我在 Objective C 中编写了以下代码,我正试图在 Swift 中使用这些代码 3. Swift 3 中似乎没有一些等效的函数.这里的代码是Objective C

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

以及我目前在 Swift 3 中的努力,它编译并运行但没有给出正确的答案。

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

这是一种可能的方法。请注意 identifierForVendor returns UUID in Swift 3. UUID 有一个 uuid 属性 给你一个 uuid_t. uuid_t 是一个包含 16 个 UInt8 值的元组。

所以诀窍是将字节元组转换为字节数组。然后从数组创建 Data 就很简单了。

if let vendorIdentifier = UIDevice.current.identifierForVendor {
    let uuid = vendorIdentifier.uuid // gives a uuid_t
    let uuidBytes = Mirror(reflecting: uuid).children.map({[=10=].1 as! UInt8}) // converts the tuple into an array
    let vendorData = Data(bytes: uuidBytes)
}

如果有人知道将 UInt8 的元组转换为 UInt8 的数组的更好方法,请说出来。

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

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

    // ...
}

Swift 4.2 (Xcode 10) 开始,您不需要制作可变的 先复制:

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

    // ...
}

我做的这个扩展似乎在不使用反射和指针的情况下工作得很好。这取决于 Swift 中的 UUID 表示为 16 UInt8 的元组,可以像这样简单地展开:

extension UUID{
    public func asUInt8Array() -> [UInt8]{
        let (u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15,u16) = self.uuid
        return [u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15,u16]
    }
    public func asData() -> Data{
        return Data(self.asUInt8Array())
    }
}

为了在 Swift 4.2 中将 UUID 翻译成 Data,我使用了这个:

let uuid = UUID()
withUnsafeBytes(of: uuid.uuid, { Data([=10=]) })

Swift 4.2 扩展

public extension UUID {

    var data: Data {
        return withUnsafeBytes(of: self.uuid, { Data([=10=]) })
    }

}