简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM