Inout parameter in async callback does not work as expected

前端 未结 4 1696
有刺的猬
有刺的猬 2020-11-29 12:26

I\'m trying to insert functions with inout parameter to append data received from async callback to an outside array. However, it does not work. And I tried eve

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 12:58

    @rintaro perfectly explained why it doesn't work, but if you really want to do that, using UnsafeMutablePointer will do the trick:

    func getOneUserApiData(path: String, c: UnsafeMutablePointer) {
        var req = NSURLRequest(URL: NSURL(string: path)!)
        var config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
        var session = NSURLSession(configuration: config)
        var task = session.dataTaskWithRequest(req) {
            (data: NSData!, res: NSURLResponse!, err: NSError!) in
            println("c before: \(c.memory)")
            c.memory++
            println("c after: \(c.memory)")
            println("thread on: \(NSThread.currentThread())")
        }
    
        task.resume()
    }
    

提交回复
热议问题