swift - How to create a global variable? -
i have global variable needs shared among viewcontrollers.
in objective-c, can define static variable, can't find way define global variable in swift.
do know of way it?
from swift programming guide
global variables variables defined outside of function, method, closure, or type context.global constants , variables computed lazily
you can define file , can access in current module
anywhere. can define in somewhere in file outside of scope.there no need static
, global variables compute lazily.
var yourvariable = "somestring"
and can access anywhere in current module.
however should avoid global variables not application state , reason of bugs.
as shown in answer in swift can encapsulate them in struct
, can access anywhere. can define static variables or constant in swift also.encapsulate in struct
struct myvariables { static var yourvariable = "somestring" }
you can use variable in class or anywhere
let string = myvariables.yourvariable println("global variable:\(string)") //changing value of myvariables.yourvariable = "anotherstring"
Comments
Post a Comment