Swift Program to Show Usage of Static keyword in Class


In Swift, static keyword is used to define or create type-level properties and method that only belongs to the class itself rather than to its instances. Or we can say that we can directly access the static properties and methods of a class with help of class itself instead of creating the instance of the class.

Algorithm

  • Step 1 − Create a class.

  • Step 2 − Inside the class define static property using static keyword and a instance property.

  • Step 3 − Also define a static method using and static keyword and a instance method.

  • Step 4 − Outside the class access the static property and method with the help of class name −

// Accessing property
NewClass.myVariable

// Calling a static function
NewClass.mynewFunc()
  • Step 5 − To access the instance property and method create instance of the class and then access them with the help of object.

// Creating an instance of NewClass
let obj = NewClass()

// Accessing an instance variable
print(obj.myVar)

// Calling an instance function
obj.myFunc()
  • Step 6 − Print the output.

Example

In the following swift example, we will first create a class named as NewClass. Inside the class, we have to define a static variable named ‘myVariable’ which can access without creating instance. We have also defined a static method named as ‘mynewFunc()’ which can also be called using the class name(without instance). Apart from static variable and method we have also defined instance variable and method in the NewClass. They are only accessed with the help of instance of the NewClass.

import Foundation
import Glibc

class NewClass {
   static var myVariable = "Hello, I am static variable"
   var myVar = 50
    
   static func mynewFunc() {
      print("Hello, I am static function")
   }
    
   func myFunc() {
      print("Hello, I am instance function.")
   }
}

// Accessing static variable
print(NewClass.myVariable)

// Calling a static function
NewClass.mynewFunc() 

// Creating an instance of NewClass
let obj = NewClass()

// Accessing an instance variable
print(obj.myVar)

// Calling an instance function
obj.myFunc()

Output

Hello, I am static variable
Hello, I am static function
50
Hello, I am instance function.

Conclusion

So this is how we can show the usage of static keyword in class. While using static keyword always remember you can’t access instance member from static context and vice versa because static member are only associated with the class itself whereas the instance members are associated with the individual instance of the class. If you to try to access the instance member from static context you will get error.

Updated on: 24-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements