Swift中的局部变量和全局变量

时间:2022-06-03 09:07:50

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

我有一段简单的代码,我想我正在使用本地和全局变量。但是,我很难理解这里出了什么问题。我首先设置“var hhhh:Int = 0”。然后,在if语句中,我将“hhhh = appleCount [”count“]设置为!Int”。由于appleCount [“count”]不为零并且有一些值,hhhh得到它的'值(我试过uisng一个打印语句,而hhhh在if语句中不是零),但是,后来当我用print打印hhhh时(“( hhhh)“)如果,我的价值再次为零。它与局部变量和全局变量有关吗?我试图在代码中与Parse通信。非常感谢您的帮助

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

}

2 个解决方案

#1


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.

它与局部变量和全局变量无关。它与后台线程有关。参数标签“block”之后的括号{}中的代码将在稍后的后台线程中运行。

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.

您的打印(hhhh)在块有机会改变之前运行.hhhh。将print语句移回块内,以便可以看到正在设置的变量。

#2


0  

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.

骨质反应帮助我理解了这个问题。非常感谢你。除了考文的反应之外,我只是想补充一点,我的问题的主要部分即将到来,因为我试图对我试图在Parse中保存的对象进行一些数学运算。所以,我还想到我可以创建一个数组,将我的对象保存在该数组中,然后访问该键并更新值。这是我现在正在使用的示例代码。它对Parse中保存的两个不同对象进行一些数学运算,并在屏幕上更新标签的文本。为了访问Parse中的两个对象并更新它们,我正在使用一个数组。

Hope the answers here will help someone in future as the awesome people of * 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])
    }
}

#1


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.

它与局部变量和全局变量无关。它与后台线程有关。参数标签“block”之后的括号{}中的代码将在稍后的后台线程中运行。

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.

您的打印(hhhh)在块有机会改变之前运行.hhhh。将print语句移回块内,以便可以看到正在设置的变量。

#2


0  

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.

骨质反应帮助我理解了这个问题。非常感谢你。除了考文的反应之外,我只是想补充一点,我的问题的主要部分即将到来,因为我试图对我试图在Parse中保存的对象进行一些数学运算。所以,我还想到我可以创建一个数组,将我的对象保存在该数组中,然后访问该键并更新值。这是我现在正在使用的示例代码。它对Parse中保存的两个不同对象进行一些数学运算,并在屏幕上更新标签的文本。为了访问Parse中的两个对象并更新它们,我正在使用一个数组。

Hope the answers here will help someone in future as the awesome people of * 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])
    }
}