函数中的完成处理程序
Completion handler in function
我有一个看起来像这样的函数,我尝试在下面的代码中添加一个 completionHandler
:
func getValueFromAPI(completionHandler: (_ result: Bool) -> Void){
apii.getVehicle(id!).done {
(vehicle: Vehicle) -> Void in
print("ggg.state: \(vehicle.state!)")
print("ggg.state: \(vehicle.displayName!)")
apii.getAllData(vehicle).done { (extendedVehicle: VehicleExtended) in
let entryBattery = (extendedVehicle.chargeState?.batteryLevel)!
let entryCarState = (extendedVehicle.state)!
print("entryBattery: \(entryBattery)")
print("entryCarState: \(entryCarState)")
completionHandler(true)
}.catch { (error) in
print("ERROOOOR: \(error)")
}
}.catch { error in
print("errorr: \(error)")
}
}
我已经尝试添加一个完整的处理程序,但在这些行中出现以下错误:
Line: apii.getVehicle(id!).done {
Error: Escaping closure captures non-escaping parameter 'completionHandler'
Line: apii.getAllData(vehicle).done { (extendedVehicle: VehicleExtended) in
Error: Escaping closure captures non-escaping parameter 'completionHandler'
我做错了什么,我该如何解决?
我正在使用 Swift 5.
您需要将 completionHandler
声明为转义闭包。例如:
func getValueFromAPI(completionHandler: @escaping (Bool) -> Void) {
...
}
注意 @escaping
限定符。
我有一个看起来像这样的函数,我尝试在下面的代码中添加一个 completionHandler
:
func getValueFromAPI(completionHandler: (_ result: Bool) -> Void){
apii.getVehicle(id!).done {
(vehicle: Vehicle) -> Void in
print("ggg.state: \(vehicle.state!)")
print("ggg.state: \(vehicle.displayName!)")
apii.getAllData(vehicle).done { (extendedVehicle: VehicleExtended) in
let entryBattery = (extendedVehicle.chargeState?.batteryLevel)!
let entryCarState = (extendedVehicle.state)!
print("entryBattery: \(entryBattery)")
print("entryCarState: \(entryCarState)")
completionHandler(true)
}.catch { (error) in
print("ERROOOOR: \(error)")
}
}.catch { error in
print("errorr: \(error)")
}
}
我已经尝试添加一个完整的处理程序,但在这些行中出现以下错误:
Line: apii.getVehicle(id!).done {
Error: Escaping closure captures non-escaping parameter 'completionHandler'
Line: apii.getAllData(vehicle).done { (extendedVehicle: VehicleExtended) in
Error: Escaping closure captures non-escaping parameter 'completionHandler'
我做错了什么,我该如何解决?
我正在使用 Swift 5.
您需要将 completionHandler
声明为转义闭包。例如:
func getValueFromAPI(completionHandler: @escaping (Bool) -> Void) {
...
}
注意 @escaping
限定符。