Mochi
Mochi

Reputation: 1117

Why does the actual body of a closure never gets executed?

From Apple's Swift Programming Language (Swift 5.2 Beta)

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
       print("Declaring Function")
}

// Here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure(closure: {
    // closure's body goes here
       print("Without Trailing Closure Syntax")
})

// Here's how you call this function with a trailing closure instead:

someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
       print("Trailing Closure Syntax")
}

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 5.2 beta).” Apple Books.

In these examples, it only prints Declaring Function twice when someFunctionThatTakesAClosure gets called twice, I'm wondering how the body of the these two closures didn't get called?

Upvotes: 0

Views: 48

Answers (1)

AdamPro13
AdamPro13

Reputation: 7400

You need to change to the following:

func someFunctionThatTakesAClosure(closure: () -> Void) {
   print("Declaring Function")
   closure()
}

Upvotes: 2

Related Questions