1

This will, I'm sure, point out my knowledge gap. But I don't seen anything about this in the S.O. knowledge banks and looking at the foundation code has not shed any light for me.

Basic question: why does Swift's Data print differently than NSData?

e.g.

func getData(_ data:Data) {
    print("The TLV was: \(data as NSData)")
}

prints:

The TLV was: <020101>

But ...

func getData(_ data:Data) {
    print("The TLV was: \(data)")
}

prints:

The TLV was: 3 bytes

Thanks.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
addzo
  • 845
  • 3
  • 13
  • 37
  • 2
    Because it's rarely useful to print out the full output of a data object containing more than a few bytes. – rmaddy Jun 29 '17 at 16:43
  • Hrmm rmaddy appears to be correct! The practical seems to outweigh the habitual. Drat. Here's a link I found while searching for something else that supports rmaddy and answers the original question inadvertently. https://stackoverflow.com/questions/40276322/hex-binary-string-conversion-in-swift/40278391#40278391 Thanks rmaddy – addzo Jun 29 '17 at 16:46
  • One option to see the bytes of a `Data` instance would be use `dump(data)` (although this prints out the bytes in decimal, not hex). Just bridging to `NSData` is a nice and easy way of seeing them in hex. – Hamish Jun 29 '17 at 16:51
  • Thanks Hamish: to give an example: The TLV was: 3 bytes ▿ 3 bytes - count: 3 ▿ pointer: 0x00000001c00117f0 - pointerValue: 7516264432 ▿ bytes: 3 elements - 2 - 1 - 1 – addzo Jun 29 '17 at 16:53
  • (although note that `Data`'s dump output only includes the byte values if there are less than 64 bytes) – Hamish Jun 29 '17 at 17:30

1 Answers1

0

"Data from Swift 3 has no "built-in" method to print its contents as a hex string, or to create a Data value from a hex string."

rmaddy was right.

Also see:

hex/binary string conversion in Swift

addzo
  • 845
  • 3
  • 13
  • 37