Skip to content

Instantly share code, notes, and snippets.

@efremidze
Created March 10, 2026 06:40
Show Gist options
  • Select an option

  • Save efremidze/0bb25a45266b025d8a3a127408d53e95 to your computer and use it in GitHub Desktop.

Select an option

Save efremidze/0bb25a45266b025d8a3a127408d53e95 to your computer and use it in GitHub Desktop.
/*
Demonstrates how Swift closures capture variables.
Without a capture list:
The closure captures the variable itself.
With a capture list:
The closure captures the value of the variable at creation time.
For reference types, that value is the reference.
*/
class SomeObject {
var value: Int = 0
}
func withCaptureList() {
print("With Capture List")
var someObject = SomeObject()
someObject.value = 1
let closure = { [someObject] in
print(someObject.value)
}
someObject = SomeObject() // variable now points to new object
someObject.value = 999
closure() // prints 1
}
func withoutCaptureList() {
print("Without Capture List")
var someObject = SomeObject()
someObject.value = 1
let closure = {
print(someObject.value)
}
someObject = SomeObject()
someObject.value = 999
closure() // prints 999
}
withCaptureList()
withoutCaptureList()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment