Daily iOS
Memory and ARC

How closure capture works

What actually happens in memory when a closure captures an outside variable? Using the output of the code below, explain the difference between using a capture list [x] and not using one.

var count = 0
let a = { print(count) }
let b = { [count] in print(count) }
count = 10
a(); b()
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Without a capture list the var itself is promoted to a heap box shared with the closure, so a() prints 10; [count] copies the value at creation time, so b() prints 0.

Share a question