How can I print the content of a variable of type Data using Swift? [duplicate]
Asked Answered
A

2

26

All I am looking to do is take a string and get its hex value. I've been following this post. Here is the code I have in my playground:

let str = "Say Hello to My Little Friend"
let data = str.data(using: String.Encoding.utf16)
print("\(data!)")

However, my code just prints:

"60 bytes\n"

How can I print the hex value? For reference, it should be:

5361792048656c6c6f20746f204d79204c6974746c6520467269656e64
Average answered 17/10, 2016 at 13:52 Comment(0)
E
37

Just

print(data! as NSData)

PS: Your expected hex is .utf8

Eanore answered 17/10, 2016 at 13:54 Comment(0)
B
58

Since Data is a Sequence of UInt8, you could map each byte to a string and then join them:

data.map { String(format: "%02x", $0) }.joined()
Brevier answered 17/10, 2016 at 14:2 Comment(2)
I like this better than the accepted answer because it gives the programmer complete control of the output format.Syllogize
var dataMap = data.map { String(format: "%02x", $0)}.joined(); print("(dataMap)")Cowberry
E
37

Just

print(data! as NSData)

PS: Your expected hex is .utf8

Eanore answered 17/10, 2016 at 13:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.