简体   繁体   English

为什么Swift不允许对非可选类型使用弱引用?

[英]Why Swift disallows weak reference for non-optional type?

This is not pure curiosity, there is a feeling that I may misunderstand something about weak references in Swift. 这并不是纯粹的好奇心,我可能会误解一些关于Swift中弱引用的东西。

Suppose I create a class from a View Controller and pass its reference to the initialiser: 假设我从View Controller创建一个类,并将其引用传递给初始化程序:

class = MyClass(vc: self)

Since the storyboard and window already keep a reference to this View Controller, it seems logical for MyClass to have a weak reference to it (for the similar reason all references created within IB are weak by default): 由于情节提要和窗口已经保留了对该View Controller的引用,因此MyClass对它的弱引用似乎是合乎逻辑的(出于类似原因,默认情况下,在IB中创建的所有引用都是弱的):

class MyClass: NSObject {
    private weak var viewController: UIViewController

    init(vc: UIViewController) {
       self.viewController = vc
       super.init
    }

    func setViewController(_ vc: UIViewController) {
       self.viewController = vc
    }

    ...
}

However this code gives compilation error, as viewController variable isn't optional. 但是,此代码会产生编译错误,因为viewController变量不是可选的。 So I had to add '!' 所以我必须加'!' to viewController declaration and remove the initialiser, leaving only setViewController which looks rather unnatural. 查看viewController声明并删除初始化程序,只剩下看起来很不自然的setViewController

What is the reason behind disallowing non-optional weak data? 禁止非可选的弱数据的背后原因是什么?

The very definition of a weak variable is that the variable does not increase the reference count of the object and, more importantly for your question, the variable's value will automatically be set to nil when the referenced object gets deallocated. weak变量的确切定义是,该变量不会增加对象的引用计数,更重要的是,对于您的问题,当释放所引用的对象时,变量的值将自动设置为nil

Since the variable must allow for a nil value, it must be optional. 由于变量必须允许一个nil值,因此它必须是可选的。 This is why non-optional weak variables are disallowed. 这就是为什么不允许非可选的弱变量。

Do not declare viewController to be implicitly unwrapped (using ! ). 不要声明viewController被隐式解包(使用! )。 Make it a proper optional (using ? ). 将其设置为适当的可选项(使用? )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM