美文网首页
swift中懒加载的then语法

swift中懒加载的then语法

作者: 蔡俊宇 | 来源:发表于2016-09-23 23:33 被阅读461次

    原文:
    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(&copy)
        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语法

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