Swift 闭包值捕获范围

Swift Closure Value Capture scope

我有一个使用 Swift 的问题 3,我试图从我的完成闭包中访问任务变量,但它不可用。如果我尝试访问块内的 "task" 我得到 "error: use of unresolved identifier 'task'" 我做错了什么?

typealias completionHandler = (data: Data?, httpResponse: HTTPURLResponse?, validServer: Bool, serverRealm: String?, serverVersion: String?) -> Void
typealias failureHandler = (data: Data?, response: URLResponse?, error: NSError?) -> Void


func ping(address: String, completionBlock: completionHandler, failureBlock: failureHandler?) -> URLSessionDataTask? {
    guard var addressComponents = URLComponents(string: address) else {
        let error = NSError(domain: "PING", code: 99, userInfo: [NSLocalizedDescriptionKey : "Invalid URL: \(address)"])
        failureBlock?(data: nil, response: nil, error: error)
        return nil
    }
    addressComponents.path = Paths.ping.rawValue
    let request = URLRequest(url: addressComponents.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: gsTimeout)

    //--------------------------------------------------------------------------------
    //  Ping the server and process the repsonse
    //--------------------------------------------------------------------------------
    var task: URLSessionDataTask!
    task = session.dataTask(with: request) { (data, response, error) in
    print("Task: \(task)")
        if error == nil {
            if let response = response as? HTTPURLResponse {
                let results = self.parseHeader(response)
                print("Results: \(results)")
                if results.isServer == true {
                    completionBlock(data: data, httpResponse: response, validServer: results.isServer, serverRealm: results.realm, serverVersion: results.serverVersion)
                } 
            }
        } else {
            failureBlock?(data: data, response: response, error: error)
        }
    }

    task.taskDescription = Paths.ping.rawValue
    task.resume()
    return task
}

现在更新了工作代码。如果您在块内使用它,则任务可用。谢谢大家

您的代码没有任何问题。它编译得很好。

您在调试器中暂停时无法使用 LLDB po task 的值,因为您暂停在完成块内。您从未在此代码中捕获 task (您没有引用它),因此它不在此处的范围内。只有在闭包内部 实际引用 的外部范围才会被闭包捕获。