原文:
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
}()
//在尾隨閉包中實(shí)例化了UILabel時(shí)的寫法
lazy var label : UILabel={
$0.text = "我是占位文字,textFiled改變時(shí)我也會改變"
$0.font = UIFont.systemFontOfSize(16)
return $0
}(UILabel())
//文章開始時(shí)給出的then代碼段,使得初始化更簡潔
let label = UILabel().then {
$0.textAlignment = .Center
$0.textColor = .blackColor()
$0.text = "Hello, World!"
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。