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 
    } /* w  ww . j  a v a  2 s .c  o  m*/
    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