- 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.
- 企業數字化創新引擎:企業級PaaS平臺HZERO
- ETL數據整合與處理(Kettle)
- SQL Server 2012數據庫技術與應用(微課版)
- SQL Server 2008數據庫應用技術(第二版)
- INSTANT Apple iBooks How-to
- 區塊鏈技術應用與實踐案例
- 大數據分析:R基礎及應用
- Deep Learning with R for Beginners
- 基于數據發布的隱私保護模型研究
- 精通Neo4j
- Access 2013 數據庫管理與應用從新手到高手
- Hands-On Big Data Analytics with PySpark
- UnrealScript Game Programming Cookbook
- 數據質量管理:數據可靠性與數據質量問題解決之道
- 零基礎學SQL