xcodeswiftglobalflagsviewdidload

How to create global variable in 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

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

var initialLoadFlag: Bool = false

And then check for it thenceforth:

if initialLoadFlag {
   showWelcomeMessage() 
}

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

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

(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.)

Thanks for your help.


Solution

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