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?
viewController
, when the strong references to it expire? – Alexander