函数在处理另一个函数的completionHandler之前返回结果,如何修复它



我遇到了这样一个问题,我不知道解决这个问题的方法是什么。

首先,假设我有以下功能

func summ(x: Int, y: Int, completionHandler: @escaping (Int) -> ()) {
let result: Int = x + y
completionHandler(result)
}

接下来,在另一个函数中,我们希望以某种方式处理上述函数的结果,并返回处理后的值。

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
}

但当我调用let resultString = getResult(x = 15, y = 10)时,我只得到一个空字符串。当我试图找到错误时,我意识到在这个方法中,它创建了let resultString: String = "",然后立即返回这个变量return resultString,并且只有在completionHandler开始工作之后

马克-下面的解决方案不适合我,因为我上面提到的方法只是一个例子,在一个真实的项目中,我需要从函数中返回正确的值,以便进一步使用它。

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

所以它正在返回"quot;因为sum函数需要时间才能完成。在getResult函数中,由于sum函数需要时间才能完成"在getResult函数中。因此,getResult应该是这样的。

func getResult(x: Int, y: Int, completion: (String) -> Void) {
let resultString: String = ""
summ(x, y) { result in
resultString = "Result: (String(result))" 
completion(resultString)
}
}

最新更新