How to create global variable in Swift? How to create global variable in Swift? swift swift

How to create global variable in Swift?


You can define a struct with static filed:

struct MyViewState {    static var initialLoadFlag = false}

Usage:

// SetMyViewState.initialLoadFlag = true// Getlet state = MyViewState.initialLoadFlagprintln("My view state:\(state)")

Remarks:Such hacks as singletons and global vars are usually needed in case of bad design. Maybe you can store your state in NSUserDefaults? Or store it in some session object that can be injected in any ViewController that needs to be aware about context.


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