The right way for implementation of a view hierarchy in UIViewController

Hello to everybody 👋

I and my coworkers can't solve a dispute about initialization of a view hierarchy for a long time. We implement a view hierarchy from code, without using Interface Builder. Each of us has own background experience about how it should work "right". If everything is clearly and understandably in Objective-C, there are some questions in Swift on which Apple hasn't answered.

We have three technical solutions and each of us applies own solution:

1️⃣
Code Block swift
class SomeClass: UIViewController {
private var someLabel: UILabel!
private var someSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
let someLabel = UILabel()
someLabel.text = "Test"
view.addSubview(someLabel)
self.someLabel = someLabel
let someSwitch = UISwitch()
someSwitch.isOn = true
view.addSubview(someSwitch)
self.someSwitch = someSwitch
}
}


2️⃣
Code Block swift
class SomeClass: UIViewController {
private let someLabel = UILabel()
private let someSwitch = UISwitch()
override func viewDidLoad() {
super.viewDidLoad()
someLabel.text = "Test"
view.addSubview(someLabel)
someSwitch.isOn = true
view.addSubview(someSwitch)
}
}


3️⃣
Code Block swift
class SomeClass: UIViewController {
private lazy var someLabel = UILabel()
private lazy var someSwitch = UISwitch()
override func viewDidLoad() {
super.viewDidLoad()
someLabel.text = "Test"
view.addSubview(someLabel)
someSwitch.isOn = true
view.addSubview(someSwitch)
}
}


I suppose that the same question has already discussed here, but I haven't found a discussion. If you know where there was the discussion, please, send to me.

I haven't found a discussion.

Neither have I.

I guess, the most preferred way by Apple would be using Interface Builder:
Code Block
class SomeVC: UIViewController {
@IBOutlet private weak var someLabel: UILabel!
@IBOutlet private weak var someSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
}
}


If you do not prefer Apple's way, unless you have some reason to be forced to use 1️⃣ or 3️⃣, I would use 2️⃣.
For only one reason that it can represent someLabel and someSwitch may not be replaced.

But, as already noted, I have never found this sort of discussion in the dev forums, so not sure my opinion would be sort of leading or not.
If you create programmatically, you need to define the frame or create constraints to position correctly the label in view.

But I do prefer using IB. Much simpler and it lets other understand what the UI design is. A big plus when working in team.
The right way for implementation of a view hierarchy in UIViewController
 
 
Q