简体   繁体   English

转换数据? 在 swift 5 中包含到 Int 的字节

[英]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.我从 iOS 上的 ble 外设的一个特性中读取了一些数据,当我尝试打印它们时,它只显示 2 个字节。 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?我的问题是,将该值转换为可读整数,swift 5 中最快的最佳实践是什么?

If I try to print characteristic.value it just says "2 bytes".如果我尝试打印特性值,它只会显示“2 个字节”。 characteristic.value is an optional Data type. features.value 是可选的数据类型。


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!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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