如何在Swift中创建全局变量? [英] How to create global variable in Swift?

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

问题描述

我正在尝试设置全局变量.就我而言,只是一个布尔标志,用于指示是否是第一次显示视图:

I am trying to set a global variable. In my case, just a boolean flag that indicates if a view is being presented for the first time:

var initialLoadFlag: Bool = true

呈现视图后,我想将此标志设置为false:

After the view is presented, I want to set this flag to false:

var initialLoadFlag: Bool = false

然后从头检查:

if initialLoadFlag {
   showWelcomeMessage() 
}

因此,我想将initialLoadFlag创建为全局变量.在哪里以及如何?我尝试过:

So, I would like to create initialLoadFlag as a global variable. Where and how? I've tried:

  • 在我的视图控制器的viewDidLoad区域
  • 在我的AppDelegate.swift文件中的application()方法中
  • AppDelegate类中
  • In the viewDidLoad area of my view controller
  • In the application() method in my AppDelegate.swift file
  • In the AppDelegate class

没有运气.我收到Use of unresolved identifier 'initialLoadFlag'错误消息

No luck. I'm getting a Use of unresolved identifier 'initialLoadFlag' error message

(注意:我意识到,在这个问题中,我背叛了我对Swift如何处理范围的无知.请原谅我……我已经到了最后期限,对语言还是陌生的.)

(Note: I realize that in this question I betray my ignorance of how scope is handled in Swift. Please forgive me... I'm on a deadline, and still new to the language.)

感谢您的帮助.

推荐答案

您可以将标志存储在主控制器中,并在对详细信息控制器执行segue时将其设置为true.例如

You could store a flag in the master controller and set it to true when you perform the segue to the details controller. E.g.

class MasterViewController: UIViewController {

    var firstTimePresenting = true

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showDetail" {
            if firstTimePresenting {
                println("First time!")
                firstTimePresenting = false
            }
        }
    }
}

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

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