我有以下代码:
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
所以,我很困惑。我该怎么做?
答案 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!) { }
}