Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an @IBOutlet be assigned let instead of var in Swift?

Tags:

xcode

ios

swift

I'm following a tutorial on Swift and I noticed that the author uses var instead of let when declaring an @IBOutlet variable. So I became curious as to why I can't use let instead since an object's properties are still mutable even if the object is constant or is this not the case?

The error Xcode shows when using let is

@IBOutlet attribute requires property to be mutable

but I'm confused because questionLabel is a UILabel object and not necessarily a property of an object. Or is the questionLabel object a property of the current viewController?

import UIKit

class ViewController: UIViewController {

    @IBOutlet let questionLabel: UILabel!

}

Thank you in advance if I'm over analyzing.

like image 771
Laurence Wingo Avatar asked Oct 23 '17 15:10

Laurence Wingo


1 Answers

The @IBOulet marked properties are generally properties of a ViewController that are connected using the interface builder. The view you create in the interface builder has to actually connect the interface elements in it to the properties during your actual application runtime.

For that reason it firstly creates a new ViewController using some init without connecting any interface elements. They only get connected at a later stage. For the runtime to be able to hook the properties up to the view elements after the object creation has completed they cannot be constants, they have to be mutable. Because they do not have a value after the initializer has finished they have to be optionals. And to not make using the properties cumbersome afterwards they are implicitly unwrapped optionals, so that you do not have to write label!.property but label.property suffices.

That is why your code crashes as soon as you try to do something with an IBOutlet variable which you failed to connect and that is also the reason why you cannot use / change / manipulate those fields in the initializer.

Regarding your actual var / let confusion. Yes, the object itself that is referenced using let can be changed, e.g. the text of a UILabel BUT the actual object reference cannot be changed. That would mean that if you do not give the constant a specific value in the initializer it would forever remain nil.

like image 51
luk2302 Avatar answered Oct 06 '22 02:10

luk2302