Lately, I started learning UIKit programmatically, and I noticed different approaches of writing and organizing your UI code.
The first one is, declaring a constant with a closure, which will execute immediately and returns a certain UI element.
Example (1st Approach):
let mainLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.text = "dummy text..."
//...
return v
}()
The second one is, declaring a UI element computed var, which is a read-only var that returns a certain UI element.
Example (2nd Approach):
var mainLabel: UILabel {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.text = "dummy text..."
//...
return v
}
And the third one is, declaring a factory function to create the UI element, and return it.
Example (3rd Approach):
private func createMainLabel(with text:String) -> UILabel {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.text = text
//...
return v
}
Now, I assume 2nd and 3rd options are quite similar, both creating a new UI element instance every time, and the 1st approach is creating that element only once. But I'd like to understand if there's more to it, why would I use one over the other, what counts as best practice, and also, are there more preferred ways to write UI code that I didn't mention here?