I'm getting a Can't unwrap Optional.None
error when running a slightly modified version of the Master-Detail App in Swift.
All I did was add a second UILabel
to the DetailViewController, right under the pre-existing detailDescriptionLabel
, and when I navigate to the DetailViewController from the MasterViewController I crash on the statement which sets my new Label:
secondLabel.text = "This is the Second Label"
I declare this label is as followed:
@IBOutlet var secondLabel : UILabel
What's really interesting is that the pre-existing code for setting the detailDescriptionLabel
includes the new optional let
syntax:
if let label = self.detailDescriptionLabel {
label.text = "This is the Detail View"
}
So why is it that we need a let
statement here for detailDescriptionLabel
? It was never declared as an Optional Label, it was declared like any regular Label IBOutlet property, like so:
@IBOutlet var detailDescriptionLabel: UILabel
so why is it being treated as an Optional?
And does this mean that from now on any object I add as an IBOutlet will also have to go through this sort of let
statement if I want to set it through code?
EDIT:
I'm crashing in the following method, on the line anotherLabel.text = "Second Label"
:
func configureView() {
// Update the user interface for the detail item.
if let theCar: CarObject = self.detailItem as? CarObject {
if let label = self.detailDescriptionLabel {
label.text = theCar.make
}
anotherLabel.text = "Second Label"
}
}
but when I treat anotherLabel
with the whole if let
business, as follows, it works perfectly well:
if let label2 = self.anotherLabel {
label2.text = "Second Label"
}