swift中懒加载的then语法

原文:
Swift:让人眼前一亮的初始化方式

then语法

  import Foundation

 public protocol Then {}

 extension Then where Self: Any {
     /// Makes it available to set properties with closures just after initializing.
///
///     let label = UILabel().then {
///         $0.textAlignment = .Center
///         $0.textColor = UIColor.blackColor()
///         $0.text = "Hello, World!"
///     }
public func then(@noescape block: inout Self -> Void) -> Self {
    var copy = self
    block(©)
    return copy
}
 }

 extension Then where Self: AnyObject {
/// Makes it available to set properties with closures just after initializing.
///
///     let label = UILabel().then {
///         $0.textAlignment = .Center
///         $0.textColor = UIColor.blackColor()
///         $0.text = "Hello, World!"
///     }
public func then(@noescape block: Self -> Void) -> Self {
    block(self)
    return self
 }
}

extension NSObject: Then {}


  //textFiled的常用懒加载模式
private lazy var textFiled : UITextField={
    let textFiled = UITextField()
    textFiled.placeholder = "请输入文字"
    return textFiled
}()

  //在尾随闭包中实例化了UILabel时的写法
 lazy var label : UILabel={
    
    $0.text = "我是占位文字,textFiled改变时我也会改变"
    $0.font = UIFont.systemFontOfSize(16)
    
    return $0
}(UILabel())


//文章开始时给出的then代码段,使得初始化更简洁
 let label = UILabel().then {
  $0.textAlignment = .Center
  $0.textColor = .blackColor()
  $0.text = "Hello, World!"
}

你可能感兴趣的:(swift中懒加载的then语法)