Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 509
user481610 Avatar asked Oct 17 '16 13:10

user481610


People also ask

How do you print the value of a variable in Swift?

In Swift, you can print a variable or a constant to the screen using the print() function.

How do I print on the same line in Swift?

Swift – Print without New Line To print to console output without a new line as trailing character using print() statement, pass empty string for the parameter terminator .

How do you add a variable to a string in Swift?

To create a String variable in Swift, declare the variable as String, or assign empty string to the variable, or assign new String instance to the variable.


2 Answers

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() 
like image 59
kennytm Avatar answered Sep 23 '22 20:09

kennytm


Just

print(data! as NSData) 

PS: Your expected hex is .utf8

like image 27
vadian Avatar answered Sep 20 '22 20:09

vadian