【问题标题】:The function returns the result before processing the completionHandler of another function, how to fix it? [duplicate]该函数在处理另一个函数的completionHandler之前返回结果,如何解决? [复制]
【发布时间】: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


    【解决方案1】:

    所以它返回 "" 因为 sum func 需要时间才能完成。在 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)
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-09
      • 2018-01-01
      • 1970-01-01
      • 2022-01-26
      • 2016-04-22
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多