【发布时间】:2018-05-07 17:30:20
【问题描述】:
我将一些函数链接在一起,一旦所有函数都运行完毕,我不知道如何调用带有返回值的完成处理程序。
func getAirQuality(completion: (aqi: Int?) -> Void) {
callAPI()
}
private func callAPI() {
// ... get data
self.parseDataForAQI(data: data)
}
private func parseDataForAQI(data: Data) {
let aqi = aqi
// Send aqi up to completion handler in getAirQuality
}
所以当一切都说完了,我可以做这样的事情:
getAirQuality(completion: { aqi -> Void in {
// Do something with aqi
})
【问题讨论】:
-
你必须在 getAirQuality 中调用 completion(aqi: Int?)
-
将完成保存在最后一个函数可以看到的地方,并在该函数完成时调用它。
-
如果您不介意使用 3rd 方库,PromiseKit 使链接异步函数调用比使用完成处理程序更容易。
标签: swift chaining completionhandler