While using the CoreBluetooth framework to setup the device as a peripheral manager, I'm running into difficulties with how Swift handles enumerations.
Specifically, the initializer for CBMutableCharacteristic takes an enum
for the properties
argument:
init!(type UUID: CBUUID!, properties: CBCharacteristicProperties, value: NSData!, permissions: CBAttributePermissions)
CBCharacteristicProperties
is an Int
-backed enumeration. If using ObjectiveC, the initializer would accept multiple values for properties
by using the bitwise OR |
operator. In Swift, the enum
does not directly allow use of bitwise OR, but one can perform it on the rawValues
that back the cases:
let properties = CBCharacteristicProperties.Read.rawValue | CBCharacteristicProperties.Notify.rawValue
Now, properties
is of type Int
, which means it can not be passed to the above initializer. ( 'Int' is not convertible to 'CBCharactersiticProperties'
) Therefore, I attempted to create an instance of the enumeration from the "raw" value:
let cbProperties = CBCharacteristicProperties(rawValue: properties)
However, at runtime this resolves to nil
. The Int
that results from the bitwise OR does not match any of the enum
cases. Passing nil
for the properties
parameter to the initializer results in a runtime error.
Is it possible to accomplish this in 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)
The syntax is Swift is exactly the same as in Objective C - Use the | character to separate the values -
var someCharacteristic=CBMutableCharacteristic(type: CBUUID(string:"someUUID"),
properties:CBCharacteristicProperties.Read|CBCharacteristicProperties.Write ,
value: nil,
permissions: CBAttributePermissions.Readable|CBAttributePermissions.Writeable)
Update While this syntax works on iOS with Xcode 6.2 it doesn't work for an OS X target - looks like a bug
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.