Serialization in Swift

Great news.

Combining this with the idea from another thread you may even do all strings (and other long enough value types like arrays / dictionaries) "GIdentifiable":

extension String: GIdentifiable {
    public var gID: [UInt8]? {
        valueIdentifier(self)
    }
}

where:

func valueIdentifier<T>(_ value: T) -> [UInt8] {
    let size = MemoryLayout.size(ofValue: value)
    var id: [UInt8] = []
    withUnsafeBytes(of: value) { p in
        let bytes = p.baseAddress!.assumingMemoryBound(to: UInt8.self)
        for i in 0 ..< size {
            let byte = bytes[i]
            id.append(byte)
        }
    }
    return id
}

func valueHexIdentifier<T>(_ value: T) -> String {
    let id = valueIdentifier(value)
    return id.reduce("") { r, e in r + String(format: "%02x", e) }
}

test:

func makeStringCopy(_ string: String) -> String {
    String(data: string.data(using: .utf8)!, encoding: .utf8)!
}

let a = makeStringCopy("Hello New World, Long enough string")
let b = a
let c = makeStringCopy("Hello New World, Long enough string")

let d = makeStringCopy("short string")
let e = d
let f = makeStringCopy("short string")

let aid = valueHexIdentifier(a) // 23000000000000f09001110200600000
let bid = valueHexIdentifier(b) // 23000000000000f09001110200600000 // same
let cid = valueHexIdentifier(c) // 23000000000000f0e001110200600000 // different

let did = valueHexIdentifier(d) // 73686f727420737472696e67000000ec
let eid = valueHexIdentifier(e) // 73686f727420737472696e67000000ec // same
let fid = valueHexIdentifier(f) // 73686f727420737472696e67000000ec // same

print(aid)
print(bid)
print(cid)
print(did)
print(eid)
print(fid)

precondition(aid == bid, "should be the same")
precondition(aid == bid, "will be different")
precondition(did == eid, "should be the same")
precondition(did == fid, "most likely will be the same due to tagged strings optimisation")

print()

Note that this automatically generated identifier generates relatively short (say 16 byte) identifier that will be equal for the same values (in the "let b = a" meaning of sameness) but may be different for values that are otherwise equal (in the "a == b" meaning of equal). This ID is not as good as the one provided manually, but, perhaps, better than no ID at all, and the good thing about it - it is automatically generated, e.g.:

extension Array: GIdentifiable {
    public var gID: [UInt8]? {
        valueIdentifier(self)
    }
}

Would be interesting to see how this works in real-world tests.