1

so i'm doing my first app, and i want to do a function that will be a uniform funciton to sevral places in the system, and not belong to only one specific class. Is there a way for me to pass a callback function as a parameter to another function ?

here is just a demonstration of what i mean.

ClassA {

   func classAcallbackFunction (displayString: String) {
     print (displayString)
   }


   ClassB().classBFunction(classAcallbackFunction())


}

ClassB {

   func classBfunction (myCallbackfunc: func) {
     mycallbackfunc("all is working !!!")
   }

}

1 Answer 1

4

The parameter you have declared is not correct. Replace it with something like this:

func classBFunction(_ completion: (String) -> Void) {
    completion("all working")
}

Like shared by regina_fallangi in the comments, callbacks are usually called completion handlers, which is why I replaced the names accordingly.

Extra Credit:

If you only want to optionally pass a function, you could do this:

func classBFunction(_ completion: ((String) -> Void)? = nil) {
    completion?("all working")
}

Now you could also just call classBFunction().

Sign up to request clarification or add additional context in comments.

4 Comments

A small nit: callback is the theoretical name and the one used predominantly in JavaScript. Swift uses completion, which gives it a different meaning. You should always call your completion, no matter what happens. If there is an error, the you should call completion(error), if there was success, completion(true), etc.
Another small nit: Underscore and parameter label are Swift 2 legacy, in Swift 3+ it's simply (String) -> Void as the parameter label is not used anyway.
If a completion should always be called, what should we call a high order function that isn't necessarily called, like a button click. A callback?
@vadian the parameter label may be important in situations where the type itself doesn't clarify what function should be passed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.