I'm little bit confused about using static keyword in swift. As we know swift introduces let keyword to declare immutable objects. Like declaring the id of a table view cell which most likely won't change during its lifetime. Now what is the use of static keyword in some declaration of struct like:
struct classConstants
{
static let test = "test"
static var totalCount = 0
}
whereas let keyword do the same.In Objective C we used static to declare some constant like
static NSString *cellIdentifier=@"cellId";
Besides which makes me more curious is the use of static keyword along with let and also var keyword. Can anybody explain me where to use this static keyword? More importantly do we really need static in swift?
to see the difference between type properties and / or methods and class properties and / or methods, please look at this self explanatory example from apple docs
Static properties may only be declared on type, not globally. In other words static property === type property in Swift. To declare type property you have to use static keyword.
I will break them down for you:
var
: used to create a variablelet
: used to create a constantstatic
: used to create type properties with eitherlet
orvar
. These are shared between all objects of a class.Now you can combine to get the desired out come:
static let key = "API_KEY"
: type property that is constantstatic var cnt = 0
: type property that is a variablelet id = 0
: constant (can be assigned only once, but can be assigned at run time)var price = 0
: variableSo to sum everything up var and let define mutability while static and lack of define scope. You might use
static var
to keep track of how many instances you have created, while you might want to use justvar
for a price that is different from object to object. Hope this clears things up a bit.Example Code:
"The let keyword defines a constant" is confusing for beginners who are coming from C# background (like me). In C# terms, you can think of "let" as "readonly" variable.
(answer to How exactly does the “let” keyword work in Swift?)
Use both
static
andlet
to define constantWhenever I use
let
to define constant, it feels like I am usingreadonly
of C#. So, I use bothstatic
andlet
to define constant in swift.A static variable is shared through all instances of a class. Throw this example in playground:
When you change the variable for the static property, that property is now changed in all future instances.
Static Variables are belong to a type rather than to instance of class. You can access the static variable by using the full name of the type.
Code:
Hope this helps you..