skip to Main Content

I am referring to the case below. The comments explain it well.

class HelloWorldViewController: UIViewController {
    
    var label: UILabel! //Why do this and then create an instance of UILabel and assign it to 'label'
    
    //When this can be done straight away?
    //var label = UILabel()
    
    override func loadView() {
        view = UIView()
        
        label = UILabel()
        label.text = "Hello World"
        view.addSubview(label)
    }
}

2

Answers


  1. I don’t think the implicitly unwrapped optional is that popular, except when used in conjunction with Storyboards, where it would look like:

    @IBOutlet var label: UILabel!
    

    The option which I see more often, and personally like the best is this though:

    lazy var label: UILabel = {
            let label = UILabel()
            label.text = "Hello World"
            // ...
            return label
        }()
    

    No force unwrap, no optional, no fake initialization, initialized only if needed, and can access instance variables.

    Login or Signup to reply.
  2. As @klangfarb says in their answer, implicitly unwrapped optionals are usually used for outlets attached to Storyboards or nibfiles.

    The idea is that if the Storyboard is set up and loads correctly, the outlets should not be nil. By making them implicitly unwrapped optionals, you cause an almost immediate crash, which shouldn’t make it through even the most simplistic testing. Once you verify that your outlets aren’t nil, not having to unwrap them every time you refer to them makes your code cleaner.

    If you create your UI with code there’s no good reason to use optionals of any kind. Lazy vars, as klangfarb suggests, are an elegant way to create your UIKit components in code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search