【发布时间】:2022-01-05 10:05:53
【问题描述】:
我遇到了这样的问题,我不知道有什么方法可以解决这个问题。
首先,假设我有以下功能
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 才开始工作
MARK - 下面的解决方案不适合我,因为我上面指出的方法只是一个示例,在实际项目中,我需要从函数中返回正确的值才能进一步使用它。
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
}
}
【问题讨论】:
标签: ios swift xcode completionhandler