Created
March 10, 2026 06:40
-
-
Save efremidze/0bb25a45266b025d8a3a127408d53e95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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