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

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.

主站蜘蛛池模板: 微博| 繁昌县| 泽普县| 通州市| 吉林市| 佳木斯市| 高雄县| 门头沟区| 绵竹市| 宁强县| 军事| 东宁县| 田林县| 陇西县| 富顺县| 斗六市| 吴川市| 南部县| 论坛| 兰考县| 雷波县| 珲春市| 长葛市| 民乐县| 尼勒克县| 清苑县| 宜都市| 兴文县| 阳原县| 阜新| 东光县| 庆云县| 明光市| 筠连县| 龙胜| 苗栗县| 木兰县| 湟中县| 改则县| 玉山县| 平顶山市|