斯威夫特没有得到设定

时间:2015-04-02 01:07:51

标签: ios swift

我尝试在下载图像后设置图像变量。我正在使用' inout'将图像变量传递给我的下载功能,但它没有设置。

这是我的代码:

var img: UIImage?

func downloadImage(url: String?, inout image: UIImage?) {

    if url != nil {

        var imgURL: NSURL = NSURL(string: url!)!
        var request: NSURLRequest = NSURLRequest(URL: imgURL)

        NSURLConnection.sendAsynchronousRequest(request, queue: 
            NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,
            data: NSData!,error: NSError!) -> Void in

            if error == nil {
                dispatch_async(dispatch_get_main_queue(), {

                    // setting img via inout doesn't work
                    image = UIImage(data: data) // inout img should be set but its not
                    println(img) 

                    // setting img directly works, but don't want it hard coded
                    img = UIImage(data: data)
                    println(img)

                })
            }
            else {
                println("Error")
            }
        })
    }
}

downloadImage(<<IMAGE URL HERE>>, &img) // passing img as an inout

我期待在下载图像后设置作为inout传递给downloadImage函数的变量img,但它永远不会更新。

我期待这一行:image = UIImage(data: data)更新img inout变量,但它没有。

但是,直接引用img变量的行img = UIImage(data: data)会更新。

但我不想直接在函数中对img变量进行硬编码,我希望能够通过inout传递我想要的任何变量。

知道为什么我无法更新inout变量以及如何解决它。 感谢。

1 个答案:

答案 0 :(得分:2)

您需要将'延续'传递给downloadImage()函数;继续是如何处理下载的图像:像这样:

func downloadImage(url: String?, cont: ((UIImage?) -> Void)?) {
  if url != nil {

    var imgURL: NSURL = NSURL(string: url!)!
    var request: NSURLRequest = NSURLRequest(URL: imgURL)

    NSURLConnection.sendAsynchronousRequest (request,
        queue:NSOperationQueue.mainQueue(),
        completionHandler: {
            (response: NSURLResponse!, data: NSData!,error: NSError!) -> Void in
          if error == nil {
            dispatch_async(dispatch_get_main_queue(), {
              // No point making an image unless the 'cont' exists
              cont?(UIImage(data: data))
              return
            })
          }
          else { println ("Error") }
      })
  }
}

然后你就像这样使用它:

var theImage : UIImage?

downloadImage ("https://imgur.com/Y6yQQGY") { (image:UIImage?) in
  theImage = image
} 

我已经利用了尾随闭包的语法,只需将可选的下载图像分配给所需的变量。

另外,请注意我没有检查你的线程结构;可能应该在其他队列上调用cont函数 - 但是,你得到了继续传递的意义。