首页 > 解决方案 > 自类型作为闭包中的参数

问题描述

a 的实例是否可以UIView调用执行闭包的方法,并在该闭包内部引用同一个实例?这是非通用版本:

import UIKit

public extension UIView {
    func layout(from: (UIView) -> ()) {
        from(self)
    }
}

例如,当我用 UILabel 调用它时,我无法访问例如文本对齐。是否有可能在闭包内我可以参考 UILabel?我希望这样的事情会起作用:

func layout(from: (Self) -> ()) {
    from(self)
}

但它不编译。有解决方法吗?这就是我要的:

let label = UILabel(frame: .zero)

label.layout { $0.textAlignment = .natural } // Currenly not working, since $0 = UIView.

标签: swiftgenerics

解决方案


不同的方法:具有关联类型的协议扩展。

protocol Layout {
    associatedtype View : UIView = Self
    func layout(from: (View) -> ())
}

extension Layout where Self : UIView {
    func layout(from: (Self) -> ()) {
        from(self)
    }
}

extension UIView : Layout {}

let label = UILabel(frame: .zero)
label.layout { $0.textAlignment = .natural }

推荐阅读