Created
March 20, 2026 05:23
-
-
Save codewithsanthoshofficial/c87cd3b7c38bc5c6d5b13eda9cb929b8 to your computer and use it in GitHub Desktop.
@escaping and @nonescaping closures in Swift
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
| ##Escaping | |
| ------------- | |
| func getSumOf(array: [Int], handler: @escaping (Int) -> Void) { | |
| // Step 2: Move work to async queue | |
| DispatchQueue.global().async { | |
| var sum: Int = 0 | |
| for value in array { | |
| sum += value | |
| } | |
| // Step 4: Call later | |
| handler(sum) | |
| } | |
| } | |
| func doSomething() { | |
| // Step 1: Call function | |
| self.getSumOf(array: [16,756,442,6,23]) { [weak self] sum in | |
| // Step 5: Executed later | |
| print(sum) | |
| } | |
| // Step 3: This runs immediately (before sum is printed) | |
| print("Function call finished") | |
| } | |
| ##Non-Escaping | |
| ------------- | |
| func getSumOf(array: [Int], handler: (Int) -> Void) { | |
| // Step 2: Do work immediately | |
| var sum: Int = 0 | |
| for value in array { | |
| sum += value | |
| } | |
| // Step 3: Call immediately | |
| handler(sum) | |
| } | |
| func doSomething() { | |
| // Step 1: Call function | |
| self.getSumOf(array: [16,756,442,6,23]) { sum in | |
| // Step 4: Executed immediately | |
| print(sum) | |
| } | |
| // Step 5: Runs AFTER closure execution | |
| print("Function call finished") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment