Static and Class Keyword in Swift

Before we talk about how static and class keyword are different with each other, lets see how they are similar.

How They Are Similar?

Static and Class keyword when applied on a variable or function, make it Type method.

Type Methods are the methods which you can call directly without creating instance of the class. Whereas, in Instance Method, we need to create an instance of the class first to access the property. Below is an example which will help you understand better.

class Employee  {
    
    var name = "Keshu"
    class var id : Int {
        return 007
    }
}

print(Employee.id) // Type Method : Accessing id directly on type. Without creating instance.
print(Employee().name) // Instance Method : Creating Instance then accessing name

Difference: Static and Class

STATICCLASS
Can be applied on Stored Property as well as Computed Properties.Can only be applied on Computer Properties.
Static method declaration are allowed in Struct as well as Classes.Class keyword can only be used in Classes.
NOTE: Static properties can not be overridden by inheriting classes.NOTE: Class properties can be overridden by inheriting classes.

static keyword is same like final class. final keyword makes the variable or function final i.e. they can not be overridden by any inheriting class.

class Employee  {
    
    static var name = "Keshu"
    class var id : Int {
        return 007
    }
}

class EmployeeAddress : Employee {
    
    override static var name = "Keshu New Name" // Error : Cannot override with a stored property 'name'
    
    override class var id: Int { // Runs successfully.
        return 100
    }
}

As you can see in above code, the static property can not be overridden by EmployeeAddress class. Whereas the id property has successfully been overridden. This is the major difference between Static and Class Keyword. I hope its clear to you now. If any queries, feel free to ask in comments.

Also, do you know what are Variadic Functions? Variadic Functions in Swift

Leave a Comment