Static Keyword in Swift

Payal Kandlur
1 min readFeb 10, 2022

We know that a var will create a variable and let will create a constant.

Static will create type properties which can be a let or a var, which can be shared between all objects of that specific class.

What this means is adding a static keyword to an object’s properties and methods lets us use them without the need of creating an instance.

//Type
class Person() {
static let userType = "Registered User"

var name: String
var age: Int
}
//Instances
let user1 = Person(name: "John", age: 20)
let user2 = Person(name: "Cindy", age: 20)

It is very important to know what is a type and what is an instance. In the above example, we can see the type which is Person and the user1 and user2 are its instances.

static let userType = "Registered User"

The above line makes every Person instance have the constant userType. Much like a global variable! So every user you create will have the userType constant.

To access that all you have to do is use the dot operator. Type dot the static variable/constant.

Person.userType

Now if you run this it will print “Registered user”.

Swift allocates them directly into the object’s memory, making it available for use without the need for an instance.

Static also is useful when you want to have a Singleton pattern in your app.

That’s all!😊 Drop in your suggestions in the comment section.

--

--