Swift - Function capturing value


A function can "capture" a value and use it multiple times.

Consider the following example code:


func myMethod(incrementAmount: Int) -> () -> Int {  
    var amount = 0  
    func incrementor() -> Int {  
        amount += incrementAmount  //from  ww w.  ja v a 2 s.c  om
        return amount 
    return incrementor  

var incrementByTen = myMethod(incrementAmount: 10)  
var a = incrementByTen() // 10  
a = incrementByTen() // 20 
var incrementByFifteen = myMethod(incrementAmount: 15)  
a = incrementByFifteen() // 15  


The myMethod function takes an Int parameter and returns a function.

Inside the function, a variable called amount is created and set to 0.

A new function is created inside the myMethod function.

Inside this new function, the amount variable has the incrementAmount parameter added to it, and then returned.

The amount variable is outside of this function.

The incrementor function is then returned.

The myMethod function can now be used to create a new incrementor function.

Each time this function is called, it will return a value that's 10 higher than the last time it was called.

The function that myMethod returned captured the variable amount.

The amount variable is not shared between individual functions.

When a new incrementor is created, it has its own separate amount variable.

The second function increments the value by 15.

Swift allows you to create functions that act as generators, functions that return different values each time they're called.

Related Topic