Capturing Values
Part of the Logic & Flow section of Coddy's Swift journey — lesson 40 of 56.
A closure remembers the variables that were in scope when it was created. The closure body can read and even modify them later, even after the surrounding function has returned. This is called capturing.
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let next = makeCounter()
print(next()) // 1
print(next()) // 2
print(next()) // 3Each makeCounter call gives you a brand-new count, so two counters never share state:
let a = makeCounter()
let b = makeCounter()
print(a()) // 1
print(b()) // 1
print(a()) // 2Capturing is what makes closures more powerful than plain functions: they carry state with them. You'll see the same trick in JavaScript, Python, and many other languages.
Challenge
MediumBuild a small counter factory.
Define a function makeCounter(start: Int, step: Int) that returns a closure of type () -> Int. Each call to the closure returns the next value: the first call returns start, the next returns start + step, the next start + 2*step, and so on.
Read three integers from input: start, step, and n. Build a counter with start and step, then call it n times and print every result on its own line.
For input 5 / 3 / 4, the output is:
5
8
11
14Cheat sheet
Closures capture variables from their surrounding scope, carrying state even after the outer function returns:
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let next = makeCounter()
print(next()) // 1
print(next()) // 2Each call to the factory function creates an independent captured variable — two counters never share state.
Try it yourself
let start = Int(readLine()!)!
let step = Int(readLine()!)!
let n = Int(readLine()!)!
// TODO: makeCounter(start:step:) -> () -> Int that captures the running value
// then call it n times and print each result
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check8Closures
Closure BasicsTrailing ClosuresCapturing ValuesReturning ClosuresCustom Higher-OrderRecap - Pipeline Builder