Q:

Put variable values in an asynchronous function in Swift

I implemented the image download function.
However, I found that the UI was stalled and I had the function asynchronous.
"(value) in" Passes the value safely, but if code try to put the value in a global variable, it will not be executed.
Code:
var arr = 0

ImageDownload(url: urll!) // asynchronous function
{   (value) in  // value = Image Height
    DispatchQueue.main.async
        {
            arr = value 
        }
}

// I want use this line
print("\(arr)")   // always print 0

ImageDownload Function : 
func ImageDownload(url urll: URL, completion: @escaping (Int) -> Void)
{
    let queue = DispatchQueue.global()
    queue.async
        {
            if let imageSource = CGImageSourceCreateWithURL(urll as CFURL, nil)
            {
                if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
                {
                    let pixelHeight = imageProperties[kCGImagePropertyPixelHeight] as! Int

                    if pixelHeight >= 2000
                    {
                        completion(pixelHeight/6)
                    }
                    else
                    {
                        completion(pixelHeight/5)
                    }
                }
            }
        }
}

Plz help me

A:

You must be using/printing arr value outside the block and before block execution.
Try moving print statement inside completion block
ImageDownload(url: urll!) { (value) in
  // value = Image Height
  DispatchQueue.main.async {
    arr = value
    print("\(arr)")
  }
}

I mean perform your operation only after arr assignment
You can use didSet of arr too.
var arr = 0 {
  didSet {
    // Add your code here you want to execute after value assignment to `arr` 
    print("\(arr)")
  }
}

