What is 'Currying'?

前端 未结 18 1584
遥遥无期
遥遥无期 2020-11-21 05:26

I\'ve seen references to curried functions in several articles and blogs but I can\'t find a good explanation (or at least one that makes sense!)

18条回答
  •  不要未来只要你来
    2020-11-21 06:08

    An example of currying would be when having functions you only know one of the parameters at the moment:

    For example:

    func aFunction(str: String) {
        let callback = callback(str) // signature now is `NSData -> ()`
        performAsyncRequest(callback)
    }
    
    func callback(str: String, data: NSData) {
        // Callback code
    }
    
    func performAsyncRequest(callback: NSData -> ()) {
        // Async code that will call callback with NSData as parameter
    }
    

    Here, since you don't know the second parameter for callback when sending it to performAsyncRequest(_:) you would have to create another lambda / closure to send that one to the function.

提交回复
热议问题