Swift: Benefits of Curry Function

梦想与她 提交于 2019-12-11 03:58:57

问题


I'm trying to grasp the concept behind curry functions. Below is the code:

class MyHelloWorldClass {

    func helloWithName(name: String) -> String {
        return "hello, \(name)"
    }
}

I can create a variable that points to the class’s helloWithName function:

let helloWithNameFunc = MyHelloWorldClass.helloWithName
// MyHelloWorldClass -> (String) -> String

My new helloWithNameFunc is of type MyHelloWorldClass -> (String) -> String, a function that takes in an instance of my class and returns another function that takes in a string value and returns a string value.

So I can actually call my function like this:

let myHelloWorldClassInstance = MyHelloWorldClass()

helloWithNameFunc(myHelloWorldClassInstance)("Mr. Roboto") 
// hello, Mr. Roboto

Credit: I go this code from this site

What is the benefit of using the above curry function? When would there a need to call a function that takes an instance of its class, that takes the subsequent parameter that was passed.


回答1:


The problem is that the example given isn't an example of currying exactly. That's why you don't see any value in it.

This is a better example of currying:

class MyHelloWorldClass {
    //Function that takes two arguments
    func concatenateStrings(string1: String, string2: String) {
        return "\(string1)\(string2)"
    }
    //Curried version of concatenateStrings that takes one argument. 
    func helloWithName(name: String) -> String {
        return concatenateStrings("hello, ", name)
    }
}

This is a better example of how function variables are curried functions in Swift: http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/



来源:https://stackoverflow.com/questions/28597324/swift-benefits-of-curry-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!