Search code examples
swiftoption-typeweak-references

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.

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?


Solution

  • 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 ?).