How do closures capture values from previous calls?

后端 未结 2 2153
时光取名叫无心
时光取名叫无心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 00:13

    You've called makeCounter() once. That creates your new closure, and assigns it to counter1. This closure closes over the mutable var n, and will remain captured as long as this closure exists.

    Calling counter1() will execute it, but it retains the same captured n, and mutates it. This particular "adder" will ALWAYS capture this same n, so long as it exists..

    To get the behavior you're suggesting, you need to make new closures which capture new instances of n:

    let counter1 = makeCounter()
    
    counter1() // returns 1
    counter1() // returns 2
    counter1() // returns 3
    
    var counter2 = makeCounter()
    counter2() // returns 1
    counter2 = makeCounter()
    counter2() // returns 1
    counter2 = makeCounter()
    counter2() // returns 1
    

    Now both counter1 and counter2 each have their own separate instances of n.

提交回复
热议问题