如何将swift的Int64
转换为UUID
并返回?由于UUID
是128位,我想用零填充前64位。
我可以UUID
uuid_t
来构建UInt8
Int64
,这是{{1}}的元组,通过移动和投射{{1}}八次。
有更好的方法吗?
答案 0 :(得分:2)
最简单的"这样做的方式(不依赖于CollectionType
或Tuple
的内存布局,并且不需要NSUUID
)是:
extension UUID {
init(number: Int64) {
var number = number
let numberData = Data(bytes: &number, count: MemoryLayout<Int64>.size)
let bytes = [UInt8](numberData)
let tuple: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0,
bytes[0], bytes[1], bytes[2], bytes[3],
bytes[4], bytes[5], bytes[6], bytes[7])
self.init(uuid: tuple)
}
var intValue: Int64? {
let tuple = self.uuid
guard tuple.0 == 0 && tuple.1 == 0 && tuple.2 == 0 && tuple.3 == 0 &&
tuple.4 == 0 && tuple.5 == 0 && tuple.6 == 0 && tuple.7 == 0 else {
return nil
}
let bytes: [UInt8] = [tuple.8, tuple.9, tuple.10, tuple.11,
tuple.12, tuple.13, tuple.14, tuple.15]
let numberData = Data(bytes: bytes)
let number = numberData.withUnsafeBytes { $0.pointee } as Int64
return number
}
}
此外,您可能需要throw
/ fatalError
而不是返回nil
。
UUID
s 为了完成(并且实际上可以创建有效的UUID),我添加了一种从2 Int64
创建它的方法,并使用它重写了您的问题的答案:
UUID
的(Int64, Int64)
创建
extension UUID {
init(numbers: (Int64, Int64)) {
var firstNumber = numbers.0
var secondNumber = numbers.1
let firstData = Data(bytes: &firstNumber, count: MemoryLayout<Int64>.size)
let secondData = Data(bytes: &secondNumber, count: MemoryLayout<Int64>.size)
let bytes = [UInt8](firstData) + [UInt8](secondData)
let tuple: uuid_t = (bytes[0], bytes[1], bytes[2], bytes[3],
bytes[4], bytes[5], bytes[6], bytes[7],
bytes[8], bytes[9], bytes[10], bytes[11],
bytes[12], bytes[13], bytes[14], bytes[15])
self.init(uuid: tuple)
}
var intTupleValue: (Int64, Int64) {
let tuple = self.uuid
let firstBytes: [UInt8] = [tuple.0, tuple.1, tuple.2, tuple.3,
tuple.4, tuple.5, tuple.6, tuple.7]
let secondBytes: [UInt8] = [tuple.8, tuple.9, tuple.10, tuple.11,
tuple.12, tuple.13, tuple.14, tuple.15]
let firstData = Data(bytes: firstBytes)
let secondData = Data(bytes: secondBytes)
let first = firstData.withUnsafeBytes { $0.pointee } as Int64
let second = secondData.withUnsafeBytes { $0.pointee } as Int64
return (first, second)
}
}
从UUID
创建Int64
(填充MSB为0)extension UUID {
init(number: Int64) {
self.init(numbers: (0, number))
}
var intValue: Int64? {
let (first, second) = intTupleValue
guard first == 0 else { return nil }
return second
}
}
答案 1 :(得分:2)
UUID
是基础类型NSUUID
的Swift叠加层类型,
后者可以从字节缓冲区创建。一点点
指针杂乱的工具也适用于64位整数:
let vals: [UInt64] = [0, 0x123456789abcdef]
let uuid = vals.withUnsafeBufferPointer {
$0.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: 16) {
NSUUID(uuidBytes: $0) as UUID
}
}
print(uuid) // 00000000-0000-0000-EFCD-AB8967452301