官术网_书友最值得收藏!

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 lazyMarking 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.

主站蜘蛛池模板: 嘉祥县| 昌吉市| 卓资县| 乐山市| 博野县| 玉环县| 柳州市| 米易县| 丰都县| 武山县| 延吉市| 龙山县| 剑阁县| 宁陕县| 青海省| 建阳市| 恩平市| 苍山县| 离岛区| 望奎县| 财经| 广宗县| 常山县| 闽清县| 汤原县| 贺兰县| 开远市| 鹤岗市| 彰化县| 丹寨县| 大悟县| 康平县| 秦安县| 白银市| 郸城县| 霍林郭勒市| 五大连池市| 赤峰市| 洛川县| 汕尾市| 尼勒克县|