Always trying to make your code beautiful, less painful and more manageable. This is the way you treat well yourself as a developer. In this article, I will show you the most favorite way of mine to initialize a variable. That is not big a step or a revolution at all but a pack of small steps will make a revolution.

    lazy var myButton: UIButton = {
        let button = UIButton()
        button.setTitle("My Button", for: .normal)
        button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(startAction)))

        return button
    }()

Why am I using lazy initialization? The reason is that (for instance) in this case “self” is not fully initialized so you can use it in initialization closure.
So in summary when the closure executes — it’s not possible to reference other property values or self from within it.
If you don’t want to use lazy to initialize a variable, that’s fine but don’t use anything that you are not sure it was fully initialized at that time.

Take another note, however, because of the “()” at the end of the closure. This is letting Swift wizards that compile your code know that the instance is being assigned to the return type of the closure. If we were to omit this, it’s possible we could’ve assigned the actual closure itself to the instance.
There is another way to initialize with closure

    lazy var myButton: UIButton {
        let button = UIButton()
        button.setTitle("My Button", for: .normal)
        button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(startAction)))
        return button
    }

A nature, universe, science, music, love lover

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami