原文:
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!"
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。