I ran into such a problem, and I can't figure out what are the ways to solve this problem.
First, let's say I have the following function
func summ(x: Int, y: Int, completionHandler: @escaping (Int) -> ()) {
let result: Int = x + y
completionHandler(result)
}
Next, in another function, we want to somehow process the result of the above function and return the processed value.
func summ(x: Int, y: Int, completionHandler: @escaping (Int) -> ()) {
let result: Int = x + y
completionHandler(result)
}
func getResult(x: Int, y: Int) -> (String) {
let resultString: String = ""
summ(x, y) { result in
resultString = "Result: \(String(result))"
}
return resultString
}
But when I call let resultString = getResult(x = 15, y = 10)
I just get an empty string. When trying to find an error, I realized that in this method it creates let resultString: String = ""
and then immediately returns this variable return resultString
, and only After that completionHandler
starts working
MARK - The solution below does not suit me, because the methods that I indicated above are just an example, in a real project, I need to return the correct value from the function in order to use it further.
let resultString: String = ""
func summ(x: Int, y: Int, completionHandler: @escaping (Int) -> ()) {
let result: Int = x + y
completionHandler(result)
}
func getResult(x: Int, y: Int) {
summ(x, y) { result in
resultString = "Result: \(String(result))"
self.resultString = resultString
}
}