如何在Swift中初始化对象期间将self传递给初始化程序? [英] How to pass self to initializer during initialization of an object in Swift?

查看:307
本文介绍了如何在Swift中初始化对象期间将self传递给初始化程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import CoreBluetooth

class BrowserSample: NSObject, CBCentralManagerDelegate {
    let central : CBCentralManager

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

    func centralManagerDidUpdateState(central: CBCentralManager!)  { }
}

如果我在 super.init()之前放入 central = 行,那么我得到了错误:

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?

推荐答案

解决方法是使用 ImplicitlyUnwrappedOptional 所以 central 初始化为 nil 首先

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

或者你可以尝试 @lazy

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

    init() {
        super.init()
    }

    func centralManagerDidUpdateState(central: CBCentralManager!)  { }
}

这篇关于如何在Swift中初始化对象期间将self传递给初始化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆