简体   繁体   中英

Convert Data? containing bytes to Int in swift 5

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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM