ios - Swift 枚举和 CBCharacteristicProperties

标签 ios swift enums core-bluetooth

在使用 CoreBluetooth 框架将设备设置为外设管理器时,我在 Swift 处理枚举的方式上遇到了困难。

具体来说,CBMutableCharacteristic 的初始化程序为 properties 参数采用了一个enum:

init!(type UUID: CBUUID!, properties: CBCharacteristicProperties, value: NSData!, permissions: CBAttributePermissions)

CBCharacteristicProperties 是一个 Int 支持的枚举。如果使用 ObjectiveC,初始化程序将通过使用按位或 | 运算符接受 properties 的多个值。在 Swift 中,enum 不允许直接使用按位或,但可以在支持大小写的 rawValues 上执行它:

let properties = CBCharacteristicProperties.Read.rawValue | CBCharacteristicProperties.Notify.rawValue

现在,propertiesInt 类型,这意味着它不能 传递给上述初始化程序。 ('Int' 不能转换为 'CBCharactersiticProperties')因此,我尝试从“原始”值创建枚举实例:

let cbProperties = CBCharacteristicProperties(rawValue: properties)

但是,在运行时这会解析为 nil。按位 OR 产生的 Int 不匹配任何 enum 情况。将 nilproperties 参数传递给初始化程序会导致运行时错误。

是否可以在 Swift 中完成此操作?

最佳答案

objective-C :

[[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:CHARACTERISTIC_UUID]
                                   properties:CBCharacteristicPropertyNotify |
                                   CBCharacteristicPropertyRead
                                   value:nil
                                   permissions:CBAttributePermissionsReadable]

swift :

CBMutableCharacteristic(type: CBUUID(string:CHARACTERISTIC_UUID),
                                properties: [CBCharacteristicProperties.Read,CBCharacteristicProperties.Notify],
                                value: nil,
                                permissions: CBAttributePermissions.Readable)

关于ios - Swift 枚举和 CBCharacteristicProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420894/

相关文章:

objective-c - 为什么 Xcode 说它可能会泄漏?

ios - UITableView 自定义选择大小

macos - 在 AppDelegate 中丢失对 NSWindows 的引用

ios - 如何获取所有字典键('LazyMapCollection<..>'错误)

java - EnumSet 'and' 操作

spring-boot - 如何在 Spring 中将 WWW 表单字段反序列化为枚举?

ios - 什么 iOS pod 在 PrivateFrameworks/ScreenReaderCore.framework 中使用 SCRCException ?

html - iOS 视网膜图像大小限制?

ios - Swift - 占位符长文本 - 切中间

java - 由 : org. hibernate.QueryException 引起:无法解析内部枚举类的属性