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

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
主站蜘蛛池模板: 濮阳市| 剑川县| 桦甸市| 桃源县| 张家界市| 长葛市| 高清| 马龙县| 长兴县| 师宗县| 万安县| 大名县| 桂阳县| 黎城县| 白水县| 宜春市| 泸西县| 东海县| 丹棱县| 绍兴市| 永顺县| 息烽县| 板桥市| 滁州市| 清新县| 崇信县| 鄂托克旗| 京山县| 黑山县| 淮南市| 东台市| 奉化市| 尤溪县| 和田县| 昂仁县| 定州市| 克东县| 天台县| 五大连池市| 鲁甸县| 象州县|