xoogler xoogler - 4 months ago 24
iOS Question

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

Answer

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)
    }
}
Comments