fs_tigre
fs_tigre

Reputation: 10738

Am I using a closure in the following code - Understanding Closures in Swift

I'm having a hard time understanding closures when used within functions.

In the following code I created a function which gets two parameters and returns a function but since I have seen a few tutorial where they show some similar examples and they refer to them as "capturing constants and variables values using closures" but on my example I don't really see the closure.

Can I say that in the code example below incrementer() is the closure?

func incrementNumber(baseNumber:Int, increaseBy: Int) -> () -> Int {

    var baseNum = baseNumber

    func incrementer() -> Int {
        baseNum += increaseBy
        return baseNum
    }

    return incrementer
}

let increase = incrementNumber(100, increaseBy: 20)
increase()
increase()
increase()

Upvotes: 1

Views: 53

Answers (1)

leeor
leeor

Reputation: 17751

Yes. incrementer() is closing over the variables baseNum and increaseBy, since both variables are in scope when the function incrementer() is declared.

This programmers stackexchange post explains it pretty nicely. As you can see there, the example (although in javascript) looks very similar to your code here.

Upvotes: 1

Related Questions