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

Currying

Functions and closures don't have to be defined at the top level. This can be unintuitive, when coming from languages such as Objective-C and Java. Swift, like JavaScript, lets you define functions and closures anywhere in your code. Functions can also return functions. This mechanism is known as currying.

Imagine that you want to create a logger method that will print a single argument, but it will always pretend to be a string to find it easily in your logs.

Let's start with the following basic implementation:

private let PREFIX = ‘MyPrefix'

private func log(_ value: String) {
print(PREFIX + “ “ + value)
}

class MyClass {
func doSomething() {
log(“before”)
/* complex code */
log(“after”)
}
}

While this works properly in the scope of a simple class, if you need to reuse the log method or change the internal implementation, this will lead to a lot of duplication.

You can use currying to overcome that issue, as follows:

func logger(prefix: String) -> (String) ->  Void {
func log(value: String) {
print(prefix + “ “ + value)
}
return log
}

let log = logger(prefix: “MyClass”)
log(“before”)
// do something
log(“after”)

// console:
MyClass before
MyClass after
主站蜘蛛池模板: 仪陇县| 石泉县| 舟山市| 治多县| 宁城县| 阿勒泰市| 孟津县| 庆云县| 乌拉特中旗| 金山区| 水富县| 梧州市| 濮阳市| 美姑县| 秦皇岛市| 靖边县| 大同市| 嘉祥县| 营山县| 喀喇| 当涂县| 河北省| 乌拉特后旗| 大兴区| 新巴尔虎左旗| 盐池县| 临沂市| 莱阳市| 泰安市| 宜章县| 吉木萨尔县| 平凉市| 府谷县| 黔南| 华宁县| 林周县| 荃湾区| 延长县| 福清市| 泾阳县| 吴忠市|