小知识二、Then协议

145 阅读1分钟

在手写代码的时候,常常会用到一些懒加载的方式来书写控件,下面是个Then协议,不会产生循环引用的问题,代码看起来比较的紧凑,更加的直观。

public protocol Then {}

extension Then where Self: AnyObject {
    public func then( block: (Self) -> Void) -> Self {
        block(self)
        return self
    }
    /*
     let  _ = UILabel().then { (label) in
     label.backgroundColor = .blue
     label.font = UIFont.systemFont(ofSize: 18)
     label.textAlignment = .center
     label.text = "Then协议库"
     label.frame = CGRect.init(x: 20, y: 200, width: 150, height: 40)
     view.addSubview(label)
     }
     */
    
    /*
     // 2.1 (推荐)无参数,无需命名,用$取参数,可自动联想属性
     let lable = UILabel().then {
     $0.backgroundColor = .blue
     $0.font = UIFont.systemFont(ofSize: 18)
     $0.textAlignment = .center
     $0.text = "Then库写法_2.1"
     $0.frame = CGRect.init(x: 200, y: 260, width: 150, height: 40)
     view.addSubview($0)
     }
     
     lable.backgroundColor = UIColor.red
     */
}


extension UIView: Then {}