Reputation: 11
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
Upvotes: 1
Views: 1070
Reputation: 128
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)
Upvotes: 0
Reputation: 131491
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.
Upvotes: 1