Per:
@IBOutlet weak var nameLabel: UILabel!
Whenever I declare my IBOutlets, i just use var instead of weak var. But I've recently come across a few code templates that use weak var. Why do they do it? What's the added benefit?
Why is there a bang operator at the end of UILabel. I know it's required and i go along w/ it, but just asking it now.
Thanks in advance.
@IBOutlet private weak var someLabel: UILabel! Let's break this down by keyword: @IBOutlet makes Interface Builder recognize the outlet. private ensures the outlet isn't accessed outside the current class. weak is used because in most situations the owner of the outlet isn't the same as the owner of the view.
Outlets that you create will therefore typically be weak by default, because: Outlets that you create to, for example, subviews of a view controller's view or a window controller's window, are arbitrary references between objects that do not imply ownership.
You have more details about the difference between weak and strong here
When you declare an outlet in Swift, you should make the type of the outlet an implicitly unwrapped optional (!). This way, you can let the storyboard connect the outlets at runtime, after initialization.
The outlets are weak since the view elements are owned (strongly) by the view. I think it's technically OK for your view controller to have a strong reference too, but not necessary.
Weak variables are optional since they can be nil
. You can declare your outlets with ?
instead but that means using force-unwrapping or optional binding every time. Declaring them as implicitly-unwrapped optionals with !
is just a convenience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With