Chief Madog
Chief Madog

Reputation: 1507

how to pass a callback function in another function in swift?

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 !!!")
   }

}

Upvotes: 1

Views: 7053

Answers (1)

LinusG.
LinusG.

Reputation: 28952

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().

Upvotes: 4

Related Questions