【问题标题】:How to pass self to initializer during initialization of an object in Swift?如何在 Swift 中初始化对象期间将 self 传递给初始化程序?
【发布时间】:2014-08-17 22:33:23
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

    标签: ios swift core-bluetooth


    【解决方案1】:

    一种解决方法是使用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!)  { }
    }
    

    【讨论】:

    • 非常感谢@lazy。不错
    • 在某些情况下对 CBCentralManager 使用惰性是个坏主意,因为初始化蓝牙无线电需要一些时间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    相关资源
    最近更新 更多