Then是实现Swift对象初始化的一个语法糖
初始化UILabel并设置其属性
letlabel=UILabel().then{$0.textAlignment=.center$0.textColor=.black$0.text="Hello,World!"}相当于:
letlabel:UILabel={letlabel=UILabel()label.textAlignment=.centerlabel.textColor=.blacklabel.text="Hello,World!"returnlabel}()技巧在所有的NSObject子类中使用 then()
letqueue=OperationQueue().then{$0.maxConcurrentOperationCount=1}在自定义类中使用,只需进行简单扩展:
extensionMyType:Then{}letinstance=MyType().then{$0.really="awesome!"}拷贝值类型数据时候 with()
letnewFrame=oldFrame.with{$0.size.width=200$0.size.height=100}newFrame.width//200newFrame.height//100使用 do() 减少类型处理
UserDefaults.standard.do{$0.set("devxoul",forKey:"username")$0.set("devxoul@gmail.com",forKey:"email")$0.synchronize()}真实示例:finalclassMyViewController:UIViewController{lettitleLabel=UILabel().then{$0.textColor=.black$0.textAlignment=.center}lettableView=UITableView().then{$0.backgroundColor=.clear$0.separatorStyle=.none$0.register(MyCell.self,forCellReuseIdentifier:"myCell")}overridefuncviewDidLoad(){super.viewDidLoad()self.view.addSubview(self.titleLabel)self.view.addSubview(self.tableView)}}安装ForiOS8+projects with CocoaPods:
pod'Then'ForiOS8+projects with Carthage:
github"devxoul/Then"Using SwiftPackageManager:
importPackageDescriptionletpackage=Package(name:"MyAwesomeApp",dependencies:[.Package(url:"https://github.com/devxoul/Then",majorVersion:2),])
评论