1

The question may be a duplicate but I couldn't find a right & simple answer matching to the current Swift version so I decided to ask the question "again".


func mainFunction() {
   myFunction(Callback: {
        print("") // should be "send this message"
    })
}

func myFunction(Callback: @escaping () -> String) {
  // do something
  Callback(text: "send this message")
}

I'm using the code from above but I'd just get a bunch of errors. How is it possible to send via Callback(text: "send this message") the text parameter back to the callback-caller (myFunction)?

Jonas0000
  • 1,085
  • 1
  • 12
  • 36

1 Answers1

0

Define your function

You should define your function this way

func myFunction(callback: @escaping (_ text:String) -> Void) {
    callback("send this message")
}

Remember, the value you want to send back to the caller is the argument of the callback function, not the return type!

Call your function

Now you can call it and receive the "send this message" String, look

myFunction(callback: { text in
    print(text) // will print "send this message"
})

Trailing Closure Syntax

Even better when the last parameter of your function is a callback, you can use the Trailing Closure Syntax which makes your code much more easier to read.

myFunction { text in
    print(text) // will print "send this message"
}
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148