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

前端 未结 1 822
忘掉有多难
忘掉有多难 2021-01-11 12:59

I have the following code:

import CoreBluetooth

class BrowserSample: NSObject, CBCentralManagerDelegate {
    let central : CBCentralManager

    init() {
          


        
相关标签:
1条回答
  • 2021-01-11 13:22

    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!)  { }
    }
    
    0 讨论(0)
提交回复
热议问题