Function
假設今天需要一個function,如果給他一個color的String,會製造出一個”顏色-box”的String。
我們可能會這樣寫:
1 2 3 4 5 6 7 8 9 10 |
class AncientBox { func prepareBoxWith(color:String) -> String { // 處理10秒 return color + "-box" } } let anAncientBox = AncientBox() let boxColor = anAncientBox.prepareBoxWith(color: "Red") print(boxColor) |
Closure
而在我們常見的第三方庫裡,我們常常看到一些不會直接返回值的寫法,比如將返回值改寫成closure。
1 2 3 4 5 6 7 8 9 10 11 |
class OldBox { func prepareBoxWith(color:String, completion:((_ box:String) -> ())? ) { let word = color + "-box" completion?(word) } } let anOldBox = OldBox() anOldBox.prepareBoxWith(color: "white", completion: { box in print(box) }) |
可以看到,在調用的時候可以直觀的在一個function中直接做處理。
Closure With Typealias
有時候Closure的參數很多,有時候這個closure的結構出現在很多function中,比如我們常用的網路庫,都會有類似(responseData:Data, responseURL:URL,responseError:Error)這樣可以複用參數形式。
1 2 3 4 5 6 7 8 9 10 11 12 |
class NewBox { typealias boxHandler = ( (_ box:String) -> () ) func prepareBoxWith(color:String, completion:(boxHandler)?) { completion?(color) } } let aNewBox = NewBox() aNewBox.prepareBoxWith(color: "Black", completion: { box in print(box) }) |