Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 371
Ana Avatar asked Jun 26 '14 22:06

Ana


1 Answers

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!)  { }
}
like image 164
Bryan Chen Avatar answered Oct 23 '22 09:10

Bryan Chen