gpt4 book ai didi

swift2 - 当需要自引用时如何在 Swift 中初始化 CBCentralManager

转载 作者:行者123 更新时间:2023-12-02 06:05:09 25 4
gpt4 key购买 nike

初始化 CBCentralManager 实例(需要委托(delegate)并且通常指向所属类)的好方法是什么?

我可以将该属性声明为隐式展开的可选属性,但作为一般做法,这样做似乎不像 Swift,也不是很安全。

或者,我可以将该属性声明为可选属性。但由于 CBCentralManager 的初始值设定项未声明为可失败,因此这样声明实例似乎没有意义。

隐式解包可选:

class MyUnwrappedOptional: NSObject, CBCentralManagerDelegate {
var centralManager: CBCentralManager!

func init() {
super.init()

centralManager = CBCentralManager(delegate: self, queue: nil, options:nil)

// Subsequent usages of centralManager in other methods of this class don't require additional unwrapping.
centralManager.scanForPeripheralsWithServices(services, options: nil)
}
}

使用可选:

class MyOptionalClass: NSObject, CBCentralManagerDelegate {
var centralManager: CBCentralManager?

func init() {
super.init()

centralManager = CBCentralManager(delegate: self, queue: nil, options:nil)

// Subsequent usages of centralManager in other methods of this class require optional checks:
if let central = centralManager {
central.scanForPeripheralsWithServices(services, options: nil)
}

// :: or ::
central!.scanForPeripheralsWithServices(services, options: nil)
}
}

这两种方法中的哪一个更优选,还是有其他方法可以实现这一目标?

最佳答案

在初始化每个没有默认值的非lazy属性之前,无法在init方法中使用self不是可选的(默认值为nil)。

如果您总是在 init 中初始化 centralManager,并且您没有任何代码可能会导致 nil,我会说 CBCentralManager! 声明是一个不错的选择。这是隐式解包可选类型的主要目的之一。

以下是 the documentation about implicitly unwrapped optionals 的摘录:

Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

如果程序逻辑确实可能允许它在可能使用的某个时刻为nil。那么普通的可选类型就是合适的选择。

另一种可能的选择是将您的 centralManager 属性声明为 a lazy property 。如果您这样做,则在您访问它之前不会创建它,但您将能够引用 self 并将其设为非可选。当您需要创建它时,将决定您是否使用此选项。

lazy var centralManager: CBCentralManager = { [unowned self] () -> CBCentralManager in
CBCentralManager.init(delegate: self, queue: nil, options: [:])
}()

关于swift2 - 当需要自引用时如何在 Swift 中初始化 CBCentralManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33189011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com