正如Documentation提到 - Autoclosure科:Swift autoclosure如何延遲工作?
的autoclosure 可延遲評價,因爲裏面 代碼不運行,直到您調用關閉。對於有副作用或計算成本很高的代碼,延遲評估是有用的 ,因爲它允許您控制代碼的評估時間。
我無法準確理解延遲背後的邏輯是什麼。
當我試圖標準閉合和autoclosure之間進行比較:
func getMyString() -> String {
print("Reaching My String")
return "My String"
}
func testStandardClousre(closure:() -> String, isValid: Bool) {
print("Reaching Test")
if isValid {
_ = closure()
}
}
// calling:
testStandardClousre(closure: {() -> String in
return getMyString()
}, isValid: false)
當然,因爲closure
不會被執行,輸出將是:
到達測試
沒有打印「到達我的字符串」,即沒有到達getMyString()
。
如果這時候關閉標記爲@autoclosure
確切的情況下(給出相同的輸出):
func testAutoClosure(closure: @autoclosure() -> String, isValid: Bool) {
print("Reaching Test")
if isValid {
_ = closure()
}
}
// calling
testAutoClosure(closure: getMyString(), isValid: false)
那麼什麼是拖延的意思?即如何延遲工作?
下面是今天的一個例子,爲什麼拖延是有用的:https://stackoverflow.com/a/45659765/1630618 – vacawama
這是一篇很棒的博客文章,展示了autoclosure是如何產生的:https://developer.apple.com/swift/blog/?id=4 – Alexander