What are good ways to initialize an instance of CBCentralManager, which requires a delegate and is often pointing to the owning class?
I could declare the property as an implicitly unwrapped optional but doing so as a general practice seems rather not Swift-like and not very safe.
Alternatively, I can declare the property as an optional. But since CBCentralManager's initializers are not declared as failable, it doesn't seem to make sense to declare the instance as such.
Implicitly Unwrapped Optional:
class MyUnwrappedOptional: NSObject, CBCentralManagerDelegate {
var centralManager: CBCentralManager!
func init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil, options:nil)
// Subsequent usages of centralManager in other methods of this class don't require additional unwrapping.
centralManager.scanForPeripheralsWithServices(services, options: nil)
}
}
Using An Optional:
class MyOptionalClass: NSObject, CBCentralManagerDelegate {
var centralManager: CBCentralManager?
func init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil, options:nil)
// Subsequent usages of centralManager in other methods of this class require optional checks:
if let central = centralManager {
central.scanForPeripheralsWithServices(services, options: nil)
}
// :: or ::
central!.scanForPeripheralsWithServices(services, options: nil)
}
}
Is either of these more preferred or is there another way to achieve this?