Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Call closure complete method in a different function

I'd like to use a method that return a result asynchronously using the delegate pattern within a closure.

Is it possible to reference the complete block within another function within the same class?

class A {

    func performASyncTask(input:String, complete:(result:String) -> Void) {

        let obj = Loader()
        obj.delegate = self
        obj.start()
        // Loader() returns loaderCompleteWithResult(result:String) when completed
    }

    func loaderCompleteWithResult(result:String){

        // Call complete function in performASyncTask .e.g

        complete(result); // Calls the complete function in performASyncTask
    }
}
like image 493
xoogler Avatar asked Apr 17 '26 10:04

xoogler


1 Answers

I don't really understand what do you want to achieve. But you can declare function property and use it later:

class A {
    var closureSaver: ((result:String) -> Void)?

    func performASyncTask(input:String, complete:(result:String) -> Void) {
        let obj = Loader()
        obj.delegate = self
        obj.start()

        closureSaver = complete
        complete(result: "a")
    }

    func loaderCompleteWithResult(result:String){
        closureSaver?(result:result)
    }
}
like image 177
Shadow Of Avatar answered Apr 19 '26 00:04

Shadow Of