首页 > 解决方案 > 无法使用 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
    }

标签: swiftasynchronous

解决方案


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

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

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


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


推荐阅读