Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, two issues. 1) weak var 2) bang operator for @IBOutlet

Tags:

Per:

@IBOutlet weak var nameLabel: UILabel!
  1. 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?

  2. 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.

like image 781
shle2821 Avatar asked Mar 12 '15 19:03

shle2821


People also ask

What is @IBOutlet weak VAR?

@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.

Why outlets are weak in Swift?

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.


2 Answers

  1. Swift IBOutlet are weak by default (but others properties are strong by default). So both writing are the same.

You have more details about the difference between weak and strong here

  1. According to apple documentation

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.

like image 123
Jérôme Avatar answered Oct 04 '22 02:10

Jérôme


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.

like image 22
gregheo Avatar answered Oct 04 '22 04:10

gregheo