Local and global variables in Swift

advertisements

I have a simple piece of code that I guess I'm using local and global variables in it. But, I have a hard time understanding what's going wrong in here. I am setting "var hhhh:Int = 0" at first. Then, inside the if statement, I set "hhhh = appleCount["count"] as! Int". Since appleCount["count"] is not zero and has some value, hhhh gets its' value (I tried that uisng a print statement and hhhh is not zero inside if statement), but, later when I print hhhh with print("(hhhh)") outside if, I again get zero for its' value. Does it have something to do with local and global variables? I'm trying to communicate with Parse in the code by the way. Thanks a lot for your kind help

import UIKit
import Parse
class NewsPageViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad(
var hhhh:Int = 0
var tttt:Int = 0
var cccc:Int = 1

    if cccc == 1 {
        var query = PFQuery(className: "Count")
        query.getObjectInBackgroundWithId("RhC25gVjZm", block: { (object: PFObject?, error: NSError?) -> Void in
            if error != nil {
                print(error)
            } else if let appleCount = object {
                appleCount["count"] = appleCount["count"] as! Int + 1
                hhhh = appleCount["count"] as! Int
                appleCount.saveInBackground()
            }
        })
    }
    print(hhhh)
}

}


It does not have to do with local and global variables. It has to do with background threads. The code in brackets {} after the parameter label "block" will run in a background thread at a later time.

Your print(hhhh) is running before the block has had a chance to change hhhh. Move the print statement back inside the block so you can see the variable being set.