我在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($0) } let vendorData : NSData = NSData.init(bytes: uuidBytes, length: 16) let hashData = NSMutableData() hashData.append(vendorData as Data)
Martin R.. 7
所述uuid
的属性UUID
是一个C阵列导入到快速作为一个元组.使用Swift保留导入的C结构的内存布局这一事实,您可以将指向元组的指针传递给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)) } // ... }
rmaddy.. 5
这是一种可能的方式.请注意,Swift 3 中的identifierForVendor
返回具有一个属性,可以为您提供.是一个由16个值组成的元组.UUID
UUID
uuid
uuid_t
uuid_t
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
,请大声说出来.
所述uuid
的属性UUID
是一个C阵列导入到快速作为一个元组.使用Swift保留导入的C结构的内存布局这一事实,您可以将指向元组的指针传递给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)) } // ... }
这是一种可能的方式.请注意,Swift 3 中的identifierForVendor
返回具有一个属性,可以为您提供.是一个由16个值组成的元组.UUID
UUID
uuid
uuid_t
uuid_t
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
,请大声说出来.