I've added handful extension to UIView
for closure initialization:
protocol ClosureInitialization: UIView {
associatedtype View = Self
init(_ configurationClosure: (View) -> ())
}
extension ClosureInitialization {
init(_ configurationClosure: (Self) -> ()) {
self.init(frame: .zero)
configurationClosure(self)
}
}
extension UIView : ClosureInitialization {}
Thanks to it, I can initialize views more easily, e.g.:
private lazy var myLabel = UILabel {
$0.text = "Label"
$0.textColor = .myTextColor
$0.font = .myFont
}
After upgrading to XCode 13.3 / 13.3.1, it stopped compiling. The only error message I get is: error: Illegal instruction: 4
. What's more, using XCode 13.2.1 everything compiles without an error.
CodePudding user response:
Looks like Xcode doesn't like circular inheritance here: ClosureInitialization
is inherited from UIView
and UIView
declares ClosureInitialization
.
You can write it like this instead:
protocol ClosureInitialization {
associatedtype View = Self
init(_ configurationClosure: (View) -> ())
}
extension ClosureInitialization where Self: UIView {
init(_ configurationClosure: (Self) -> ()) {
self.init(frame: .zero)
configurationClosure(self)
}
}
extension UIView: ClosureInitialization {}
var myLabel = UILabel {
$0.text = "Label"
$0.textColor = .black
}