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.