While watching the Stack Views with Enums by objc.io, I learned an interesting little tidbit. You can add a convenience constructor aka convenience initializer by extending a class. The benefit of doing such is that you don’t have to subclass the class. In hindsight, the availability of that feature seems obvious. The Swift reference even has a section called “Initializers”. However, this ability may be news to others as well.
Similar to what they show at 7:45 in the video, one can write the following:
1 2 3 4 5 6 7 8 9 10 11 12 |
extension UIStackView { convenience init(labelTitles: [String]) { self.init() for title in labelTitles { let label = UILabel() label.text = title addArrangedSubview(label) } } } |
Next, you can call this new init
like any other initializer:
1 |
let stackView = UIStackView(labelTitles: ["Harry Potter", "Star Trek"]) |
I highly recommend you watch the entire Stack Views with Enums video. Enjoy!