Tuesday, February 2, 2016

Swift: Optionals?! (and IBOutlet)

I'm trying to understand Swift's concept of “optionals”. The idea is that Swift won't allow a developer to purposely set something to nil. (For simplicity, think of nil as another word for null.)
If you know that something might end up being nil (through no fault of your own, of course), you should declare the variable as an “optional” by using a question mark after the type declaration, like this:
var myInt: Int?
If you're certain that something will have a value, but you haven't given it one yet, you tell Swift using an exclamation mark:
var myInt: Int!
But, then I noticed that Xcode inserts the following when connecting a label in a view to its controller:
@IBOutlet weak var recordingLabel: UILabel!
WHAT?!
weak means that the label might not be there. It could potentially be nil.
Yet, Xcode is giving the label a !, meaning that it’s certain to have a value.
How can that be???
Well...
@IBOutlet weak var recordingLabel: UILabel!
1. -- Xcode places weak here because the View owns the label. Therefore, if the View goes away, the label should be able to go away with the View.
 -- If strong were used here, the label might still be hanging out in memory after its View is gone.
 -- I can make an assumption that my code associated with the View wouldn't be running anyway if its View weren't there. So, I don't need to force the label to stay with a strong.
2. Since I can make the assumption that my View will be present while my View Controller is running, then I can use the ! to “implicitly unwrap” the label. If the View is there, then my label will be there, too.
3. Finally, the ! is necessary to tell the compiler that I, as a developer, know the label will be there. The compiler is going to trust my judgement in this case. If the label isn't there at runtime for some reason, though, then I'll get an error.

No comments:

Post a Comment