从Swift 3中的UUID获取数据

问题描述 投票:2回答:5

我在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>($0) }
let vendorData : NSData  = NSData.init(bytes: uuidBytes, length: 16)
let hashData = NSMutableData()
hashData.append(vendorData as Data)
objective-c swift swift3 uuid
5个回答
6
投票

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

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)开始,您不需要先制作一个可变副本:

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

    // ...
}

5
投票

这是一种可能的方式。请注意,identifierForVendor在Swift 3中返回UUIDUUID有一个uuid属性,它给你一个uuid_tuuid_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({$0.1 as! UInt8}) // converts the tuple into an array
    let vendorData = Data(bytes: uuidBytes)
}

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


2
投票

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

let uuid = UUID()
withUnsafeBytes(of: uuid.uuid, { Data($0) })

1
投票

我做的这个扩展看起来很好,没有使用反射,也没有使用指针。这取决于Swift中的UUID被表示为16个UInt8s的元组,这可以简单地解开,如下所示:

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())
    }
}

0
投票

Swift 4.2扩展

public extension UUID {

    var data: Data {
        return withUnsafeBytes(of: self.uuid, { Data($0) })
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.