swift - 无法使用 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)。但它不能两者兼得,因为这些事情发生在两个不同的时间;活动是异步的,因此 Bool在活动开始之前就返回了。
推荐阅读
- php - 使用 GD 库将文本转换为图像不起作用
- forms - 为什么 Vuex 状态变量似乎绑定到组件的局部变量?
- laravel - Laravel 5.5:重定向路由并将变量传递给其他路由,然后控制器显示在视图上
- r - 函数不适用于子集中子集的数据集
- scheme - 迭代过程中的固定数量和固定规则
- python - Python Tabulate 将字符格式化为单独的列
- exception - 没有缓存值时如何抛出 CacheException
- json - 删除反斜杠但在 json 字符串中保留 unicode
- microsoft-teams - Microsoft Teams:如何禁止用户删除 Planner 中的任务?
- oop - 枚举 switch-case 样式 dynamic_cast