Search code examples
swiftuilabeliboutlet

Swift: optional or implicit UILabel?


I'm trying to follow a MakeSchool tutorial for creating my first Swift game and have a question.

When I tried to create a UILabel variable to store the outlet to the label, Swift suggested that I either make it an optional or implicitly unwrapped one.

Is there one that is a better style or safer?


Solution

  • Generally IBOutlet references would be implicitly unwrapped:

    @IBOutlet weak var label: UILabel!
    

    In fact, if you control-drag from the control in Interface Builder to create the outlet in the source code in the assistant editor for you, this is precisely what sort of outlet Xcode will create for you.

    In short, one uses an implicitly unwrapped if, once it's set, it's assumed to always be non-nil.

    You'd generally use a standard optional if it's a variable that may or may not be nil at any point in the lifecycle.