UUIDs can be generated in a distributed manner and are fairly easy to use, but they are quite long when encoding.
E2731BE6-470D-4782-B853-E5B13E8A1ECF
D879A224-9A58-4D71-8E43-B7F3D001B7E4
FFF4DCE4-3C49-459B-BDB9-EB4B5A030FEB
I want to avoid preserving this as it is.
UUIDs are usually written in hexadecimal, so if you save them as strings, you should be able to shorten them even more.
Implement ʻextension` like this.
extension UUID {
public var base64String: String {
var base64WithPadding = self.data.base64EncodedString()
//At the end of base64==Get rid of
base64WithPadding.removeLast(2)
return base64WithPadding
}
public var data: Data {
var result = Data()
let uuidTuple = self.uuid
result.append(uuidTuple.0)
result.append(uuidTuple.1)
result.append(uuidTuple.2)
result.append(uuidTuple.3)
result.append(uuidTuple.4)
result.append(uuidTuple.5)
result.append(uuidTuple.6)
result.append(uuidTuple.7)
result.append(uuidTuple.8)
result.append(uuidTuple.9)
result.append(uuidTuple.10)
result.append(uuidTuple.11)
result.append(uuidTuple.12)
result.append(uuidTuple.13)
result.append(uuidTuple.14)
result.append(uuidTuple.15)
return result
}
}
This can reduce 36 characters to 22 characters.
40CC21EA-7D27-49CC-8A18-280373933BE2 -> QMwh6n0nScyKGCgDc5M74g
2AF87112-E64C-441F-85E1-FD4FCCD097CA -> KvhxEuZMRB+F4f1PzNCXyg
D9C051E6-D7E2-4198-9CB1-A399E347D860 -> 2cBR5tfiQZicsaOZ40fYYA
Test with the code below
for _ in 0..<10 {
let id = UUID()
let data = Data(base64Encoded: id.base64String + "==")!
let uuid = UUID(uuid: (
data[0], data[1], data[2], data[3], data[4], data[5],
data[6], data[7], data[8], data[9], data[10], data[11],
data[12], data[13], data[14], data[15]
))
print(id, "->", id.base64String, "->", uuid)
}
40CC21EA-7D27-49CC-8A18-280373933BE2 -> QMwh6n0nScyKGCgDc5M74g ->
40CC21EA-7D27-49CC-8A18-280373933BE2
2AF87112-E64C-441F-85E1-FD4FCCD097CA -> KvhxEuZMRB+F4f1PzNCXyg ->
2AF87112-E64C-441F-85E1-FD4FCCD097CA
D9C051E6-D7E2-4198-9CB1-A399E347D860 -> 2cBR5tfiQZicsaOZ40fYYA ->
D9C051E6-D7E2-4198-9CB1-A399E347D860
Lossless compression is possible.
Recommended Posts