Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save codewithsanthoshofficial/c87cd3b7c38bc5c6d5b13eda9cb929b8 to your computer and use it in GitHub Desktop.

Select an option

Save codewithsanthoshofficial/c87cd3b7c38bc5c6d5b13eda9cb929b8 to your computer and use it in GitHub Desktop.
@escaping and @nonescaping closures in Swift
##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