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

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.

主站蜘蛛池模板: 治县。| 三亚市| 文化| 沙田区| 红桥区| 岑巩县| 内黄县| 南京市| 淮安市| 临汾市| 林州市| 青阳县| 昌黎县| 望谟县| 阿图什市| 宝山区| 三穗县| 西充县| 临澧县| 米泉市| 桃源县| 紫金县| 泸西县| 招远市| 绵阳市| 尼木县| 辉南县| 阿尔山市| 柳河县| 彰武县| 辰溪县| 修水县| 安阳县| 剑阁县| 油尖旺区| 太保市| 德江县| 柳州市| 蚌埠市| 苏尼特左旗| 宜章县|