How do closures capture values from previous calls?

后端 未结 2 2073
时光取名叫无心
时光取名叫无心 2021-01-04 23:51
typealias IntMaker = (Void)->Int

func makeCounter() ->IntMaker{
    var n = 0 // Line A

    func adder()->Integer{
        n = n + 1
        return n 
            


        
2条回答
  •  清酒与你
    2021-01-05 00:12

    Obviously, Line A isn't being called each time counter1 is called.

    The sequence of events is:

    • makeCounter is called, which declares and initializes n (Line A), defines adder, and returns adder in a context that includes n already having been defined and initialized to 1.

    • It is this function that was just returned that is assigned to counter1. Because the Line A is not part of that function (adder/counter1), it does not get executed when that function is called.

    • Each call to counter1 is executed in that same context, which is why n retains its value across calls: they are all accessing the same n.

提交回复
热议问题