无法使用Swift 5.3从该异步操作中获取布尔值



下面的代码将处理打印语句(成功,不成功(,但我不能在更新状态之外设置或使用该函数。有人能举一个例子说明我如何获得退货的Bool(而不仅仅是将其硬编码为true(吗?

func updateStatus( completion: @escaping (_ flag:Bool) -> ()) {
//let retVal: Bool = true
let url = URL(string: build())! //"http://192.168.1.4:6875/login")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in

if error != nil || data == nil {
print("Client error!")
completion(false)
return
}
guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
print("Server error!")
completion(false)
return
}
guard let mime = response.mimeType, mime == "text/html" else {
print("Wrong MIME type!")
completion(false)
return
}

print("Yay! Everything is working!")
completion(true)

print(data!)

/*
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
} catch {
print("JSON error: (error.localizedDescription)")
}
*/
}
task.resume()
//return retVal
}
func ping() -> Bool {
updateStatus { success in
if success {
print("success")
} else {
print("not sucess!")
}
}
return true
}

有人能提供一个例子来说明我如何获得返回的Bool(而不仅仅是将其硬编码为true(吗?

你不能。您的success完成处理程序中异步到达。你不能返回任何依赖它的东西。你必须做与updateStatus完全相同的事情,出于同样的原因——你的代码是异步的,所以为了处理它的结果,你必须调用完成处理程序

简而言之,完成处理程序模式传播异步性。你无法神奇地停止传播它。


基本上,这里的错误是ping试图在两个不同的时间做两件不同的事情:它想启动异步活动(通过调用updateStatus(,并充当异步活动的结束。但它不能两者兼而有之,因为这些事情发生在两个不同的时间;该活动是异步,因此Bool在活动开始之前返回

最新更新