SLN SLN - 1 year ago 97
iOS Question

Why the default type of the label is a forced unwrapped optional?

When I create a label in the view (dragged from the Object library) and make the IBOutlet to connect the label and viewController (Ctrl and drag), The default code generated by Xcode is, for example,

@IBOutlet weak var displayColumn: UILabel!

I can delete the exclamation mark and set it as the
only. But there must be a good reason the Xcode want it to be a forced unwrapped optional type.

Question: I don't think I understand the reason to use the optional type here. Because I already created a label in my view and connected it to my controller, it is firmly out there, it exists, I created it. Why Xcode want an option as the default type? If it says the text inside the label is an option, that sounds reasonable to me, because the label may be empty at some point in run time.

Many Thanks

Answer Source

You have created a label in Xcode and indicated to Xcode that you want that label connected to that @IBOutlet. But that connection doesn't happen until later.

This is the order of events at runtime.

  1. The viewController is created (instantiated).
  2. The Storyboard or .xib is unarchived. The label is created at this time.
  3. The @IBOutlets and @IBActions are connected.

In Swift, when a class is instantiated, all properties must be initialized. In step 1, the outlets are nil because they haven't been connected yet. In order to allow for this, they must be declared as Optionals.

It is perfectly valid to use a normal Optional, such as:

@IBOutlet weak var displayColumn: UILabel?

but then you'd have to deal with unwrapping it each time you access it. The only time an @IBOutlet will be nil is when step 3 hasn't happened yet (for example, in prepareForSegue) or if you forgot to connect the outlet or renamed it. In those cases, the crash caused by accessing nil alerts you to the problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download