Swift中的局部和全局变量 [英] Local and Global variables in Swift

查看:164
本文介绍了Swift中的局部和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段简单的代码,我想我正在使用本地和全局变量。但是,我很难理解这里出了什么问题。我首先设置var hhhh:Int = 0。然后,在if语句中,我将hhhh = appleCount [count]设置为!Int。因为appleCount [count]不是零并且具有某个值,hhhh获得它的'value(我试着用uisng打印语句,而hhhh在if语句里不是零),但是后来当我用print((嗯))在外面,如果我再次得到零的价值。它与本地和全局变量有什么关系?顺便说一下,我试图在代码中与Parse进行通信。
非常感谢您的帮助

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.

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

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.

这篇关于Swift中的局部和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆