首页 > 解决方案 > 将 UUID 转换为字符串表示,例如:1816 转换为 Cycling Speed 和 Cadence

问题描述

我正在通过蓝牙连接到 Cycling Speed and Cadence 服务,并将外围设备保存到数组中(用于 tableview)。

我已经实现了这个结构

struct BTPeripheral: Identifiable {
    let id: Int
    let name: String
    let uuid: UUID
    let desc: String
}

我打电话的是

discoveredBTDevices.append(BTPeripheral.init(
                           id: discoveredBTDevices.count, 
                           name: peripheral.name!, 
                           uuid: peripheral.identifier, 
                           desc: service.uuid.uuidstring) // trying service.uuid results in error
)

这导致了这个输出

id: 0, 
name: "Wahoo CADENCE 1DE8", 
uuid: E98F3843-1C6A-E4DE-6EF3-76B013950007, 
desc: "1816"

描述为字符串 1816(即循环 Speed & Cad 服务的 UUID)

let serviceCyclingSpeedAndCadenceUUID             = CBUUID(string: "1816")

如何将 1816 转换为打印出来的字符串“Cycling Speed and Cadence”

print(service.uuid) // this results in "cycling Speed and Cadence"

如上所述,放置service.uuid会导致错误Cannot convert value of type 'CBUUID' to expected argument type 'String'

标签: swiftcore-bluetooth

解决方案


你可以得到它description(IIRC,print最终会做什么,CBUUID符合CustomStringConvertible):

service.uuid.description

或者使用字符串插值:

"\(service.uuid)"

debugDescription也会产生相同的结果,但除非这实际上是为了调试,否则我不会使用它。


推荐阅读