marius marius - 1 month ago 17
Swift Question

How to convert Data to hex string in swift

I want the hexadecimal representation of a Data value in Swift.

Eventually I'd want to use it like this:

let data = Data(base64Encoded: "aGVsbG8gd29ybGQ=")!
print(data.hexString)

Answer

This code extends the Data type with a computed property. It iterates through the bytes of data and concatenates the byte's hex representation to the result:

extension Data {
    var hexDescription: String {
        return reduce("") {$0 + String(format: "%02x", $1)}
    }
}

This is not an efficient implementation due to the string concatenation. For every byte, there is a string allocation and copy operation being performed.