How to create and use Global Variable in swift


As per the Apple document – “Global variables are variables that are defined outside of any function, method, closure, or type context

Before we learn how to create global variables, first let us understand completely what are they.

Consider “W” which is inside the inner circle, can access everything which will be inside the inner circle. On the other hand, A can access everything which is inside the outer circle as well as everything inside the inner circle, so the scope of “A” is global as he can access both the circles.

So a global variable can access everything inside the bigger and inner circle.

Now we will see how one can declare or create Global Variable. When we define a class or a struct we can define global variables.

Now we will be seeing how to declare a global variable. We will be using the Playground.

So let’s get started, Xcode → File → Playground

class Student {
   var section: String = "A"
   func getStudentData() {
      // some function
   }
}

Here you can see section is a global variable we have defined, inside a class but outside a function. We can use an access modifier prefixed with the global variable as per the need.

You can also define a global variables as static by prefixing static keyword.

private var name: String = "Aman"

There’s another and efficient way to create and store global variable is using a struct, you should always create a struct and encapsulate all the global variable inside it and can use in any class wherever we want., Let’s see how we can do it.

struct Student {
   static let name: String="Aman"
   static let age: Int = 22
}
class Employee {
   func getData() {
      print(Student.age)
      print(Student.name)
   }
}

This is how we can create global variables in swift.

Updated on: 30-Aug-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements