美文网首页
Swift中超级方便的初始化状态设置语法糖 `Then`

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

作者: __Simon__ | 来源:发表于2018-05-28 11:37 被阅读19次

    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方法的

    相关文章

      网友评论

          本文标题:Swift中超级方便的初始化状态设置语法糖 `Then`

          本文链接:https://www.haomeiwen.com/subject/wapujftx.html