Local and Global variables in Swift

怎甘沉沦 提交于 2019-12-08 04:20:02

问题


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)
}

}


回答1:


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.




回答2:


osteven response helped me a lot understanding the problem. Thanks a lot man. In addition to osteven's response, I just waned to add that a major part of my problem was coming because I was trying to do some mathematical operations on the objects I was trying to save in Parse. So, I also figured that I could create an array, save my objects inside that array, and then access the key and update the values. Here is a sample code of what I am using right now. It does some mathematical operation on two different objects saved in Parse and updates the label's text on screen. For accessing the two objects in Parse and updating them I'm using an array.

Hope the answers here will help someone in future as the awesome people of StackOverFlow are helping me now. Peace!

var hhhh : [Int] = []
@IBOutlet weak var jPercent: UILabel!

@IBOutlet weak var yPercent: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

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

            }
        })
    } else if cccc == 2 {
        query.getObjectInBackgroundWithId("5Bq4HJbFa3", block: { (object: PFObject?, error: NSError?) -> Void in
            if error != nil {
                print(error)
            } else if let yCount = object {
                yCount["count"] = yCount["count"] as! Int + 1
                yCount.saveInBackground()
            }
        })
    }

    //shouldn't use same query for findObjectsInBackgroundWithBlock and getObjectInBackgroundWithId otherwise you'll get a runtime error
    var query2 = PFQuery(className: "Count")
    query2.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if let users = objects {
            for object in users {
                if let user = object["count"] as? Int {
                    self.hhhh.append(user)
                }

            }

        }
        var gggg = 100*Float(self.hhhh[0])/(Float(self.hhhh[0]+self.hhhh[1]))
        self.yPercent.text = String(format: "%.1f", gggg) + "%"
        self.jPercent.text = String(format: "%.1f", 100 - gggg) + "%"
        print(self.hhhh[0])
    }
}


来源:https://stackoverflow.com/questions/34254656/local-and-global-variables-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!