1

I would like to know if there is a way to create a mutable global variable in Swift? I know that I can declare constants, but I want to change the value.

Thanks

4
  • 2
    Just use var instead of let. Commented Apr 10, 2015 at 13:06
  • @Kirsteins couldn't that approach lead to weird behaviours when you try to set the variable from multiple sources at the same time? Commented Apr 10, 2015 at 13:16
  • @DánielNagy, only if you are writing multi-threaded code. In that case you better know what you are doing, and add synchronization code. Commented Apr 10, 2015 at 13:41
  • @DánielNagy Thread safety is not exclusive to this question. It should be taken into account when dealing with any variable resources. Commented Apr 10, 2015 at 13:50

2 Answers 2

1

In swift, you declare variables with var and constants with let.

If you want a global variable, create it a the top of a file, outside of the definition of any enclosing class/struct/enum/etc.

If you will access that variable from multi-threaded code as @DánielNagy mentions in his comment, it's more complex. However accessing global variables from concurrent code is best avoided.

Sign up to request clarification or add additional context in comments.

Comments

0

you can write

class myViewController : UIViewController{
struct GlobalVar{
static var myName : String?
}
override func viewDidLoad(){
super.viewDidLoad()
}
}

in any view controller and access it anywhere by:

//Another VC viewDidload
GlobalVar.myName = "Hello"
print(GlobalVar.myName)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.