I'm trying to set an image variable after an image has been downloaded. I'm using 'inout' to pass the image variable to my download function, but it doesn't get set.
Here's my code:
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
Im expecting the variable img
which is passed as an inout to the downloadImage function to be set after the image is downloaded, but it never gets updated.
I'm expecting the line: image = UIImage(data: data)
to update the img inout variable but it doesn't.
However, the line: img = UIImage(data: data
) which references the img variable directly gets updated.
But I don't want to hard code the img
variable directly within the function, I want to be able to pass any variable I want via inout
.
Any idea why I cant update the inout variable and how I can fix it. Thanks.