How to pass self to initializer during initialization of an object 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 the error:

  • Swift 2.0 - Binary Operator “|” cannot be applied to two UIUserNotificationType operands
  • ios- Check whether current time is between two times or not
  • How to access a UITextView on another ViewController
  • Converting iPhone xib to iPad xib?
  • Open WatchKit application from iOS
  • Using AnyGenerator with Swift 2.2+ (“for in” loop support for custom classes)
  • self used before super.init() call
    

    If I put it after, I get the error:

    Property self.central not initialized at super.init call
    

    So, I’m confused. How do I do this?

    Solutions Collect From Internet About “How to pass self to initializer during initialization of an object in Swift?”

    a workaround is use ImplicitlyUnwrappedOptional so central is initialized with 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!)  { }
    }