- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 220字
- 2021-07-02 14:44:59
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
推薦閱讀
- 程序員修煉之道:從小工到專家
- 數據可視化:從小白到數據工程師的成長之路
- Java Data Science Cookbook
- 信息系統與數據科學
- Voice Application Development for Android
- Hadoop 3.x大數據開發實戰
- 科研統計思維與方法:SPSS實戰
- 區塊鏈技術應用與實踐案例
- SAS金融數據挖掘與建模:系統方法與案例解析
- 算力經濟:從超級計算到云計算
- 數據產品經理寶典:大數據時代如何創造卓越產品
- 一本書講透數據治理:戰略、方法、工具與實踐
- 全球智庫評價報告(2015)
- MySQL技術內幕:InnoDB存儲引擎(第2版)
- Reactive Programming in Kotlin