Swift中超级方便的初始化状态设置语法糖 `Then`

Then Github地址,是一个很好用的初始化语法糖协议,可以在初始化之后很方便的设置相关的属性,并且将设置属性代码全部内聚在closure中,使代码看上去清晰明了。下面简单看看Then的使用

let label = UILabel().then {
        $0.textColor = UIColor.black
        $0.font = UIFont.systemFont(ofSize: 15)
        $0.textAlignment = .left
        $0.text = "default text"
    }

在Then协议中有三个方法

with & do

extension Then where Self: Any {

  /// Makes it available to set properties with closures just after initializing and copying the value types.
  ///
  ///     let frame = CGRect().with {
  ///       $0.origin.x = 10
  ///       $0.size.width = 100
  ///     }
  public func with(_ block: (inout Self) throws -> Void) rethrows -> Self {
    var copy = self
    try block(&copy)
    return copy
  }

  public func `do`(_ block: (Self) throws -> Void) rethrows {
    try block(self)
  }

}

withdo方法是对Any任意类型的扩展,只要该类型遵循了Then协议就可以使用withdo方法

with方法的实现我们能够看出来,先对执行with方法的实例做了一次复制,得到一个新的实例copy,然后再将拷贝所得的实例copy传递给block,copy将作为block中后续设置的参数,最后将被block执行之后的copy返回。如果copy是值类型那么执行with之后将得到一个新的实例,如果copy是引用类型那么执行with方法之后返回还是它自己。

then

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(_ block: (Self) throws -> Void) rethrows -> Self {
    try block(self)
    return self
  }

}

then方法是对AnyObject的扩展,也就是说只有遵循了Then协议的class的实例即对象才能使用then方法,而值类型的实例是不能使用then方法的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容