Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

xcode - 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:

  • In the viewDidLoad area of my view controller
  • In the application() method in my AppDelegate.swift file
  • In the AppDelegate class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can define a struct with static filed:

struct MyViewState {
    static var initialLoadFlag = false
}

Usage:

// Set
MyViewState.initialLoadFlag = true

// Get
let state = MyViewState.initialLoadFlag
println("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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...