快速编码中的Erorr

时间:2015-11-05 11:06:38

标签: swift

typealias NetworkResponse = (data: NSData?, response: NSURLResponse?, error: NSError?)

extension NSURLSession {

func sendSynchronousDataTaskWithRequest(request: NSURLRequest) -> NetworkResponse? {

    let semaphore = dispatch_semaphore_create(0)
    var response: NetworkResponse? = nil

    let task = dataTaskWithRequest(request) { (data :NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        response = NetworkResponse(data: data, response: response, error: error)
        dispatch_semaphore_signal(semaphore)
    }
    task.resume()
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

    return response
 }

}

无法在swift中为块内的响应变量赋值。在swift中缺少关键字__block

错误是:

  

无法分配值:'响应'是一个“让...”恒定

2 个答案:

答案 0 :(得分:1)

typealias NetworkResponse = (data: NSData?, response: NSURLResponse?, error: NSError?)

extension NSURLSession {

func sendSynchronousDataTaskWithRequest(request: NSURLRequest) -> NetworkResponse? {

    let semaphore = dispatch_semaphore_create(0)
    var res: NetworkResponse? = nil

    let task = dataTaskWithRequest(request) { (data :NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        res = NetworkResponse(data: data, response: response, error: error)
        dispatch_semaphore_signal(semaphore)
    }
    task.resume()
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

    return res
 }

}

答案 1 :(得分:0)

response更改为变量:

let task = dataTaskWithRequest(request) { (data :NSData?, var response: NSURLResponse?, error: NSError?) -> Void in

喜欢这个