81

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?

5
  • 8
    If you don't know what static is, I'd recommend you reading some OOP book before starting writing in swift. static variable is shared between all instances of an object, if it's const (let) then it is just immutable Jan 3, 2016 at 9:09
  • 4
    @DanielKrom : As per my understanding, I used static to declare some constants in C, Objective C. I don't have a knowledge beyond that. So, I thought let and static are the same.
    – Poles
    Jan 3, 2016 at 9:20
  • 12
    in C and Objective-C statics are not constants (unless you define them as constants), you probably didn't understand that well and it's fine, no one is born with knowledge, statics are kind of global variables Jan 3, 2016 at 9:30
  • static define a type property: “Type Properties Instance properties are properties that belong to an instance of a particular type. Every time you create a new instance of that type, it has its own set of property values, separate from any other instance. You can also define properties that belong to the type itself, not to any one instance of that type. There will only ever be one copy of these properties, no matter how many instances of that type you create. These kinds of properties are called type properties.” “The Swift Programming Language (Swift 3)”.
    – abanet
    Mar 2, 2017 at 21:51
  • 1
    It's a good question. When the instance property's value is fully known at compile time (e.g. let = "hello, world") then a reasonable question occurs: why use a static property over an instance property? One assumes the compiler is smart enough to optimise away repeat values. And a static property incurs a slight inconvenience factor (having to include the type namespacing before using the property).
    – Womble
    May 29, 2019 at 4:44

7 Answers 7

161

I will break them down for you:

  • var : used to create a variable
  • let : used to create a constant
  • static : used to create type properties with either let or var. 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 constant
  • static var cnt = 0 : type property that is a variable
  • let id = 0 : constant (can be assigned only once, but can be assigned at run time)
  • var price = 0 : variable

So 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 just varfor a price that is different from object to object. Hope this clears things up a bit.

Example Code:

class MyClass{
    static let typeProperty = "API_KEY"
    static var instancesOfMyClass = 0
    var price = 9.99
    let id = 5

}

let obj = MyClass()
obj.price // 9.99
obj.id // 5

MyClass.typeProperty // "API_KEY"
MyClass.instancesOfMyClass // 0
4
  • "let : used to create a constant" => variable declared with let keyword can be assigned (only once) later (i.e. in constructor) which is contradictory to the definition of CONSTANT. If we compare with other languages such as C# then let is same as C# readonly (not const) Oct 3, 2017 at 4:27
  • what is equivalent to static let in objective c because I have to define the uiaplicationdidenterbackground in view controller Apr 13, 2018 at 5:41
  • 3
    Although I believe its technically correct you never gave an example of why I would ever need static over let.
    – ICW
    Sep 3, 2018 at 18:52
  • To be more clear, a static var will have the same value in every instances of a class while a var will be a unique variable in each class.
    – T.J.
    Feb 26, 2022 at 16:21
130

A static variable is shared through all instances of a class. Throw this example in playground:

class Vehicle {
    var car = "Lexus"
    static var suv = "Jeep"
}

// changing nonstatic variable
Vehicle().car // Lexus
Vehicle().car = "Mercedes"
Vehicle().car // Lexus

// changing static variable
Vehicle.suv // Jeep
Vehicle.suv = "Hummer"
Vehicle.suv // Hummer

When you change the variable for the static property, that property is now changed in all future instances.

3
  • Vehicle().car, giving Lexus , but, let vehObj = Vehicle(); vehObj.car, giving Mercedes . I don't know why. Whats the diff? Can u Guide me?
    – McDonal_11
    Jul 8, 2019 at 7:27
  • vehObj.car is giving me Lexus, I don't know why you're getting Mercedes
    – Bobby
    Jul 9, 2019 at 19:39
  • Let suv = Vehicle(); suv.suv // Jeep; let suv2 = Vehicle(); suv2.suv = "Hummer"; let suv3 = Vehicle(); suv3.suv // Hummer; If I then go "suv.suv" will it return "Jeep" or "Hummer"? Does the value change for all instances of that object, or just future instances? If it only changes for future instances, why is that? Why not all instances? Sorry if this is a stupid question. I guess I've not seen much application of static variables. Jun 5, 2020 at 20:56
13

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:

class IOS {

  var iosStoredTypeProperty = "iOS Developer"

  static var swiftStoredTypeProperty = "Swift Developer"

 }

 //Access the iosStoredTypeProperty by way of creating instance of IOS Class

let iOSObj = IOS()

print(iOSObj.iosStoredTypeProperty)  // iOS Developer


 //print(iOSObj.swiftStoredTypeProperty) 
 //Xcode shows the error 
 //"static member 'swiftStoredTypeProperty' cannot be used on instance of type IOS”


 //You can access the static property by using full name of the type
print(IOS.swiftStoredTypeProperty)  // Swift Developer

Hope this helps you..

1

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

class SomeClass {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        return 27
    }
    class var overrideableComputedTypeProperty: Int {
        return 107
    }
}

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.

2
  • 1
    You are explaining static by using static itself. The OP isn't reallly aware of its meaning...
    – mfaani
    May 19, 2016 at 12:51
  • 3
    @asma22 ?? Keyword static has totally different meaning in swift and c language. Static in swift means 'type' (property or function). The difference between 'static' and 'class' property or function is that 'class' property or function could be overridden, 'static' could not be owerriden. Because most people with background use 'static' in other context, apple commensing to use 'type' word for explanation, even though the keyword is 'static' May 19, 2016 at 15:23
1

"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 and let to define constant

public static let pi = 3.1416            // swift

public const double pi = 3.1416;         // C#
public static final double pi = 3.1416   // Java     

Whenever I use let to define constant, it feels like I am using readonly of C#. So, I use both static and let to define constant in swift.

1

Let me explain it for those who need Objective-C reference.

Hope you all remember that we were using a constant file in our Objective-C project to keep all the static API keys like below.

/ In your *.m file
static NSString * const kNSStringConst = @"const value";

Here the keyword Static does not mean that the kNSStringConst is a constant, it just defines that the kNSStringConst can be accessed globally. They keyword const makes it constant.

Now let's move to Swift.

In Swift, Static let and Static var are considered as Type Properties, which means that they can be accessed by their type.

For Example:

class World {
   static let largestPopulation = "China"
   static var secondLargestPopulation = "India"
}

World.largestPopulation = "German"   // Cannot assign to property: 'largestPopulation' is a 'let' constant
World.secondLargestPopulation = "UK"
World.secondLargestPopulation // UK

In this example, two properties have static keyword, one is constant and another one is variable.

  1. As you can see, the constant Static let declared can be accessed by it's type, but cannot be changed.
  2. The Static var declared can not only be accessed by it's type but also can be modified. Consequently, all the future instances will be changed.
0

[Swift's property]
[var vs let]
[class vs static]

In a nutshell class and static are type property and belongs to Type in a single copy

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.