0

I read from a characteristic of a ble peripheral on IoS some data, and when I try to print them, it just says 2 bytes. Looking at the type it is a optional Data type (Data?).

My question is, to convert that value to a readable integer, what is the best as fastest practice in swift 5?

If I try to print characteristic.value it just says "2 bytes". characteristic.value is an optional Data type.


switch characteristic.uuid:

   case accelerometerUUID:
      if characteristic.value != nil {
            let accelValue = ???
            print(accelValue)
      }

Thank you very much!

modusT
  • 89
  • 1
  • 3
  • 1
    It depends. Could you do `print(characteristic.value as NSData)`. Depending on the result and what's the value behind it, you need to convert that String output into a String with `Int(String(data: characteristic.value, encoding: .utf8))` or https://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data – Larme Apr 10 '19 at 10:46

1 Answers1

-1

Try this:

guard let value = characteristic.value else { return } // This makes it non-optional
let stringInt = String(data: value, encoding: .utf8)
let yourNumber = Int(stringInt)

This is much safer than the example below. The one above should be preferred.

In one line of code:

let yourNumber = Int(String(data: characteristic.value!, encoding: .utf8))

This is unsafe because you are unwrapping a value that might be optional, this can result in a crash.

Hope this helps!

Oscar
  • 404
  • 7
  • 19
  • Thank you for your answer. I tried it right now and I faced two issues; the first is that it keeps printing "2 bytes", and the second is that i needed to use the *guard* both for the stringInt and yourNumber value – modusT Apr 10 '19 at 11:02