问题描述
typealias IntMaker = (Void)->Int
func makeCounter() ->IntMaker{
var n = 0 // Line A
func adder()->Integer{
n = n + 1
return n
}
return adder
}
let counter1 = makeCounter()
counter1() // returns 1
counter1() // returns 2
counter1() // returns 3
每次调用 / code>?这意味着
var n = 0
应该每次调用...
Isn't 'Line A' called each time we call counter1()
? meaning that var n = 0
should be called every time...
为什么计数器返回不同的值?
Why is that the counter returns different values? Shouldn't they always be returning '1' ?
推荐答案
你已经调用 makeCounter / code>一次。这将创建您的新闭包,并将其分配给
counter1
。这个闭包关闭了可变的 var n
,只要这个闭包存在,它就会被捕获。
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.
code> counter1()将执行它,但它保留相同的捕获 n
,并将其改变。这个特定的加法器总是捕获这个相同的 n
,只要它存在..
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..
您需要创建新的闭包,捕获 n
的新实例:
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
现在 counter1
和 counter2
每个都有自己的单独实例 n
。
Now both counter1
and counter2
each have their own separate instances of n
.
这篇关于闭包如何捕获来自以前调用的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!