Callback Function Syntax in Swift

Callback function syntax in Swift

Rob's answer is correct, though I'd like to share an example of a simple working callback / completion handler, you can download an example project below and experiment with the getBoolValue's input.

Swift 5:

func getBoolValue(number : Int, completion: (Bool)->()) {
if number > 5 {
completion(true)
} else {
completion(false)
}
}

getBoolValue(number: 2) { (result) -> () in
// do stuff with the result
print(result)
}

Important to understand:

(String)->() // takes a String returns void
()->(String) // takes void returns a String

How to pass callback functions in Swift

Ok, now with the full code I was able to replicate your issue. I'm not 100% sure what the cause is but I believe it has something to do with referencing a class method (displayTimeRemaining) before the class was instantiated. Here are a couple of ways around this:

Option 1: Declare the handler method outside of the SecondViewController class:

func displayTimeRemaining(counter: Int) -> Void {
println(counter)
}

class SecondViewController: UIViewController {

// ...
var timer = Timer(duration: 5, handler: displayTimeRemaining)

Option 2: Make displayTimeRemaining into a type method by adding the class keyword to function declaration.

class SecondViewController: UIViewController {

var timer: Timer = Timer(duration: 5, handler: SecondViewController.displayTimeRemaining)

class func displayTimeRemaining(counter: Int) -> Void {
println(counter)
}

Option 3: I believe this will be the most inline with Swift's way of thinking - use a closure:

class SecondViewController: UIViewController {

var timer: Timer = Timer(duration: 5) {
println($0) //using Swift's anonymous method params
}

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

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

Callbacks in iOS swift 3

Another way (use Optional to delay giving object its real value until initialization has otherwise fully taken place):

class ConnectBLE {
var callBackFunc: ()->()

init(callFunc: @escaping () -> ()){

callBackFunc = callFunc
}

func runCallBackFunc() {
callBackFunc()
}
}
class DelegateARC {
private var object : ConnectBLE! //*

init() {
self.object = ConnectBLE(callFunc: RaspakHC05) // *
}

func RaspakHC05() {
print("hello from a callback")
}
}

How to add parameters to inline callback using Swift?

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

Callback syntax in swift 3

I believe you have it wrong on how to use call back closures, from what I can understand of your question you want to do something with the ticket in the call back closure and to do that it should be a parameter of the closure not the return type of the closure.

Replace your function declaration with this:

public static func functionWithCallback(params: Dictionary<String, String>, success: @escaping ((_ response: String, _ ticket: Ticket) -> Void), failure: @escaping((_ error:String) -> Void) ) {

And inside the function replace this:

success("") {
let ticket = json["ticket"] as! NSDictionary
var date = ticket["date"] as! String
var ticket: Ticket = nil // Im not sure what you are trying to do with this line but this will definitely give an error
ticket.setDate(date: date)
return ticket
}

With:

let ticket = json["ticket"] as! NSDictionary
var date = ticket["date"] as! String
var ticket: Ticket = nil // fix this line
ticket.setDate(date: date)
success("",ticket)

And then you can call the function like this:

API.functionWithCallback(params: params, success: { response, ticket in
// you can use ticket here
// and also the response text
}) { errorMessage in
// use the error message here
}

Swift callback inline function usage

There are several ways to declare or use closures. The simplest one you're looking for is probably:

{ status_code, data in
println(status_code)
}

This needs to be used in such a way that the compiler can infer the type of status_code, data, and determine that there should be no return value. For instance, you can pass it as a function parameter (what you want), or assign it to a variable with appropriate type hints.



Related Topics



Leave a reply



Submit