0

I am trying to follow the example in the Swift docs for a trailing closure.

This is the function:

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
    print("we do something here and then go back")//does not print
}

And I call it here.

        print("about to call function")//prints ok
        someFunctionThatTakesAClosure(closure: {
            print("we did what was in the function and can now do something else")//does not print
        })
        print("after calling function")//prints ok

The function, however, is not getting called. What is wrong with the above?

Here's the Apple example:

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

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

someFunctionThatTakesAClosure(closure: { // closure's body goes here })

user6631314
  • 1,751
  • 1
  • 13
  • 44
  • A closure is just a value. Just like any other value, you can "ignore" its existence and nothing would happen. Making anything happen would require you to actually use the value. – Alexander Mar 23 '19 at 00:27

2 Answers2

1

Docs isn't very clear in explanation you need

print("1")
someFunctionThatTakesAClosure() {  // can be also  someFunctionThatTakesAClosure { without ()
    print("3") 

}

func someFunctionThatTakesAClosure(closure: () -> Void) { 
   print("2") 

   /// do you job here and line blow will get you back
    closure()
}  

the trailing closure is meant for completions like when you do a network request and finally return the response like this

func someFunctionThatTakesAClosure(completion:  @escaping ([String]) -> Void) { 
   print("inside the function body") 
   Api.getData { 
      completion(arr)
   }
}  

And to call

print("Before calling the function")
someFunctionThatTakesAClosure { (arr) in
  print("Inside the function callback  / trailing closure " , arr)
}
print("After calling the function") 

what you missed to read

enter image description here

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

Here is your example fixed:

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
    print("we do something here and then go back")

    // don't forget to call the closure
    closure()
}


print("about to call function")

// call the function using trailing closure syntax
someFunctionThatTakesAClosure() {
    print("we did what was in the function and can now do something else")
}

print("after calling function")

Output:

about to call function
we do something here and then go back
we did what was in the function and can now do something else
after calling function
vacawama
  • 150,663
  • 30
  • 266
  • 294