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