匿名函數格式:swift
{ //代碼體 }()
大括號是定義函數體的,小括號()是調用函數體的。閉包
爲何不寫一個函數而後調用函數呢?爲什麼用匿名函數呢?ide
主要仍是代碼的簡潔性.函數
舉個🌰ui
private lazy var guideScrollView: UIScrollView = { let view = UIScrollView.init() view.backgroundColor = UIColor.lightGray view.bounces = false view.isPagingEnabled = true view.showsHorizontalScrollIndicator = false view.delegate = self return view }()
上述代碼簡單清晰明瞭,若是使用函數,要先寫一個函數,而後再去調用,麻煩許多,代碼也不明朗。code
當時,你也可使用閉包來這樣初始化it
private lazy var guideScrollView = { ()-> UIScrollView in let view = UIScrollView.init() view.backgroundColor = UIColor.lightGray view.bounces = false view.isPagingEnabled = true view.showsHorizontalScrollIndicator = false view.delegate = self return view }