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

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.

主站蜘蛛池模板: 大新县| 隆化县| 尼勒克县| 台南市| 阳新县| 泾源县| 沙河市| 左贡县| 广东省| 五寨县| 察隅县| 盐津县| 临安市| 南丰县| 特克斯县| 武邑县| 汶川县| 镇坪县| 满洲里市| 宽城| 泰顺县| 当阳市| 威信县| 额济纳旗| 临颍县| 庆云县| 吴堡县| 江口县| 沙坪坝区| 理塘县| 德安县| 霍山县| 白山市| 尚义县| 荣昌县| 怀远县| 红原县| 含山县| 勐海县| 章丘市| 长兴县|