Why Swift disallows weak reference for non-optional type?

巧了我就是萌 提交于 2020-01-04 15:56:08

问题


This is not pure curiosity, there is a feeling that I may misunderstand something about weak references in Swift.

Suppose I create a class from a View Controller and pass its reference to the initialiser:

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):

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. So I had to add '!' to viewController declaration and remove the initialiser, leaving only setViewController which looks rather unnatural.

What is the reason behind disallowing non-optional weak data?


回答1:


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.

Since the variable must allow for a nil value, it must be optional. This is why non-optional weak variables are disallowed.

Do not declare viewController to be implicitly unwrapped (using !). Make it a proper optional (using ?).



来源:https://stackoverflow.com/questions/52231282/why-swift-disallows-weak-reference-for-non-optional-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!