1

I have a variable with a type of Any, when I print the variable it looks like I have a json object like below:

var machineNumber: Any

NSLog("Machine number: \(machineNumber)")

the result is :

Machine number: {length = 29, bytes = 0xab002a05 0803073c 6b43fefe 6b3c0000 ... 00000000 00000000 }

my question is, how can I get the bytes out of the variable with the type Any.

Any help is appreciated!

akano1
  • 40,596
  • 19
  • 54
  • 67
  • 1
    See Rob Napier answer for the casting, then https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift might be what you are looking for. – Larme Mar 18 '21 at 16:15

1 Answers1

0

This is the string format you would get for an NSData. Assuming it really is an NSData, you would convert it to a Data. (And then, ideally, replace Any with Data in your definition. Any types a major pain to work with.)

if let data = machineNumber as? Data {
    // use `data` for the bytes
}
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • if I do that and then log the result I only get machine number: 29 bytes, how can I get the actual value for bytes from that. – akano1 Mar 18 '21 at 16:33
  • If you want the bytes as a hexadecimal string, then see https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift. If you want the bytes as a base64 string, use `.base64EncodedString(options:)`. If you want the bytes as a UTF-8 encoded string, then use `String(data:encoding:)`. If you want the actual bytes, then use the Data as a Collection. – Rob Napier Mar 18 '21 at 16:37