Back to questions
JuniorTheoryCommon
What does the program print?
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let c1 = makeCounter()
let c2 = c1
print(c1(), c2(), c1())1 2 3
- Expecting
1 1 2: thinkinglet c2 = c1copies the closure as it would copy an array. Both names lead to one closure, so they share onecount. - Expecting
1 1 1: thinkingvar count = 0runs on every call. It runs once, whenmakeCounteris called, and the closure keeps that variable.
- What does the program print if
c2is a secondmakeCounter()call instead? - Why may the closure change
counteven thoughc1is aletconstant?