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];
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)
The
uuid
property ofUUID
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 theData(bytes:, count:)
constructor:As of Swift 4.2 (Xcode 10) your don't need to make a mutable copy first:
This extension I made seems to work great without using reflection, nor pointers. It depends on the fact that UUID in Swift is represented as a tuple of 16
UInt8
s which can simply be unwrapped like so:Here's one possible way. Note that
identifierForVendor
returnsUUID
in Swift 3.UUID
has auuid
property which gives you auuid_t
.uuid_t
is a tuple of 16UInt8
values.So the trick is converting the tuple of bytes into an array of bytes. Then it's trivial to create the
Data
from the array.If anyone knows a better way to convert a tuple of
UInt8
into an array ofUInt8
, please speak up.Swift 4.2 Extension
To translate a
UUID
toData
in Swift 4.2, I used this: