- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 193字
- 2021-07-02 14:44:59
Closures, functions, and currying
Closures are blocks of code that can be executed later, and functions are a special case of closures. Functions and closures can be passed around in your code, returned by other functions or closures. You can store a closure or a function in a variable, and execute them later:
let runMe = { () -> Int in
print(“run”)
return 0
}
runMe()
The preceding code is equivalent to the following:
func runMe() -> Int {
print(“run”)
return 0
}
runMe()
Closures and functions are almost always interchangeable, except when it comes to class or struct members:
class MyClass {
var running = false
lazy var runWithClosure: () -> Void = {
self.running = true
}
func runWithFunction() {
self.running = true
}
}
While both implementations are somewhat equivalent, we rarely want this function to be overridable at runtime. The closure can't reference self inside of it, unless marked lazy. Marking it lazy forces the implementation to be var, which, in turn, doesn't reflect what we want to express. In practice, we never declare instance methods as closures.
- 同步:秩序如何從混沌中涌現
- 我們都是數據控:用大數據改變商業、生活和思維方式
- MySQL高可用解決方案:從主從復制到InnoDB Cluster架構
- Developing Mobile Games with Moai SDK
- 數據驅動:從方法到實踐
- Mockito Cookbook
- OracleDBA實戰攻略:運維管理、診斷優化、高可用與最佳實踐
- SQL優化最佳實踐:構建高效率Oracle數據庫的方法與技巧
- LabVIEW 完全自學手冊
- 大數據治理與安全:從理論到開源實踐
- 云數據中心網絡與SDN:技術架構與實現
- TextMate How-to
- 數據修復技術與典型實例實戰詳解(第2版)
- Expert Python Programming(Third Edition)
- 數據庫應用系統技術