如何在Swift中初始化对象期间将self传递给初始化程序?

时间:2014-06-26 22:30:11

标签: ios swift core-bluetooth

我有以下代码:

import CoreBluetooth

class BrowserSample: NSObject, CBCentralManagerDelegate {
    let central : CBCentralManager

    init() {
        central = CBCentralManager(delegate: self, queue: nil, options: nil)
        super.init()
    }

    func centralManagerDidUpdateState(central: CBCentralManager!)  { }
}

如果我将central =行放在super.init()之前,那么我会收到错误:

self used before super.init() call

如果我把它放在后面,我会收到错误:

Property self.central not initialized at super.init call

所以,我很困惑。我该怎么做?

1 个答案:

答案 0 :(得分:20)

解决方法是使用ImplicitlyUnwrappedOptional,因此central首先使用nil进行初始化

class BrowserSample: NSObject, CBCentralManagerDelegate {
    var central : CBCentralManager!

    init() {
        super.init()
        central = CBCentralManager(delegate: self, queue: nil, options: nil)
    }

    func centralManagerDidUpdateState(central: CBCentralManager!)  { }
}

或者您可以尝试@lazy

class BrowserSample: NSObject, CBCentralManagerDelegate {
    @lazy var central : CBCentralManager = CBCentralManager(delegate: self, queue: nil, options: nil)

    init() {
        super.init()
    }

    func centralManagerDidUpdateState(central: CBCentralManager!)  { }
}