自動閉包

定義
An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.
autoclosure是一種閉包,自動創建一個閉包用來包裹一個表達式,它可以作爲一個參數傳入一個函數。當閉包被調用的時候,不帶有任何參數並且返回包裹在閉包中的表達式的值。這種語法方便讓您可以通過編寫一個正常表達式而不是顯式閉包來忽略函數形參的括號。
正常使用閉包
這裏寫圖片描述
把閉包作爲參數
這裏寫圖片描述
自動閉包
serve(customer:)上面的列表中 的函數採用返回客戶名稱的顯式閉包。下面的版本serve(customer:)執行相同的操作,但是,它採取自動閉包,而不是採取顯式閉包,通過標記其參數的類型與@autoclosure屬性。現在你可以調用函數,就像它接受一個String參數,而不是一個閉包。參數將自動轉換爲閉包,因爲customerProvider參數的類型標記有@autoclosure屬性。
這裏寫圖片描述
注意
1.It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it.
使用自動閉包前提是:閉包不包含任何的參數。當閉包被調用的時候,返回的是包裹在閉包中的表達式的值。
2.Overusing autoclosures can make your code hard to understand. The context and function name should make it clear that evaluation is being deferred.過度的使用自動閉包可以導致代碼很難理解,函數和上下文應該清楚表明計算正在推遲。

發佈了74 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章