Swift - Function capturing value

Introduction

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

Consider the following example code:

Demo

func myMethod(incrementAmount: Int) -> () -> Int {  
    var amount = 0  
    func incrementor() -> Int {  
        amount += incrementAmount  /*from  w  w  w .  j  av  a 2  s .c o m*/
        return amount 
    } 
    return incrementor  

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

Result

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