How to pass yourself to the initializer during object initialization in Swift?

I have the following code:

import CoreBluetooth class BrowserSample: NSObject, CBCentralManagerDelegate { let central : CBCentralManager init() { central = CBCentralManager(delegate: self, queue: nil, options: nil) super.init() } func centralManagerDidUpdateState(central: CBCentralManager!) { } } 

If I put the central = line before super.init() , then I get an error:

 self used before super.init() call 

If I put it after, I get an error message:

 Property self.central not initialized at super.init call 

So, I'm confused. How to do it?

+8
ios swift core-bluetooth
source share
1 answer

The workaround uses ImplicitlyUnwrappedOptional , so central initialized to nil first

 class BrowserSample: NSObject, CBCentralManagerDelegate { var central : CBCentralManager! init() { super.init() central = CBCentralManager(delegate: self, queue: nil, options: nil) } func centralManagerDidUpdateState(central: CBCentralManager!) { } } 

or you can try @lazy

 class BrowserSample: NSObject, CBCentralManagerDelegate { @lazy var central : CBCentralManager = CBCentralManager(delegate: self, queue: nil, options: nil) init() { super.init() } func centralManagerDidUpdateState(central: CBCentralManager!) { } } 
+15
source share

All Articles