最新 XCode 不编译 UIView 的闭包初始化

Newest XCode doesn't compile closure initialization for UIView

我已经为 UIView 添加了少量扩展以用于闭包初始化:

protocol ClosureInitialization: UIView {
    associatedtype View = Self

    init(_ configurationClosure: (View) -> ())
}

extension ClosureInitialization {

    init(_ configurationClosure: (Self) -> ()) {
        self.init(frame: .zero)
        configurationClosure(self)
    }
}

extension UIView : ClosureInitialization {}

多亏了它,我可以更轻松地初始化视图,例如:

private lazy var myLabel = UILabel {
    [=12=].text = "Label"
    [=12=].textColor = .myTextColor
    [=12=].font = .myFont
}

升级到XCode13.3 / 13.3.1后,编译停止。我收到的唯一错误消息是:error: Illegal instruction: 4。更重要的是,使用 XCode 13.2.1 一切编译都没有错误。

看起来 Xcode 不喜欢这里的循环继承:ClosureInitialization 继承自 UIView 并且 UIView 声明 ClosureInitialization

你可以这样写:

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 {
    [=10=].text = "Label"
    [=10=].textColor = .black
}