Patrick
Patrick

Reputation: 867

Two returns in Closures

I'm New to swift here. Was reading closures on weheartswift. There is one section talking about capturing value. Two questions here:

  1. How do I understand the two returns here?
  2. Why this closure captures the previous value from variable, shouldn't i be initialized every time from the value of start, which is always 0?

Code :

func makeIterator(start: Int, step: Int) -> () -> Int {

    var i = start

    return {
        i += step
        return i
    }
}

var iterator = makeIterator(0, 1)

iterator() // 1

iterator() // 2

iterator() // 3

Upvotes: 2

Views: 196

Answers (2)

Narendra G
Narendra G

Reputation: 549

It is seems like function returns function as its value. returned function doesn't take any argument and returns a integer value. I recommend you to have a look at Swift documentation.

Upvotes: -1

jtbandes
jtbandes

Reputation: 118651

Like this:

var i = start
return /*the following is a closure that returns an Int:*/{
    i += step
    return i
}/*< end of closure*/

What's being returned is a closure. { return i } is actually a function that returns the value of i.

You could also write it this way:

func makeIterator(start: Int, step: Int) -> () -> Int {

    var i = start
    func iterate() -> Int {
        i += step
        return i
    }
    return iterate
}

A closure is functionality + state. The "state" here is the local variable i.

The closure "closes over" i, meaning that each time the closure is executed it will be looking at the same i which it can modify. This is true even after the closure is returned from the function. When you call it multiple times, it updates its internal state and returns the new value.

Upvotes: 2

Related Questions