How to pass self to initializer during initialization of an object in Swift?

泄露秘密 提交于 2019-12-04 00:19:04

问题


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?


回答1:


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!)  { }
}


来源:https://stackoverflow.com/questions/24441254/how-to-pass-self-to-initializer-during-initialization-of-an-object-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!