Introduction

Functions can return other functions.

You can use a function that creates a new function:

In the following code, the function takes an Int as a parameter.

It returns a new function that takes an Int parameter and returns an Int.

Demo

func createAdder(numberToAdd: Int) -> (Int) -> Int { 
    func adder(number: Int) -> Int { 
        return number + numberToAdd 
    } /*from  w ww.  ja v a2s. com*/
    return adder 

} 
var addTwo = createAdder(numberToAdd: 2) 
var a = addTwo(2) // 4 
print(a)

Result

addTwo is now a function that can be called.

Related Topic