Global Variables in Swift

Stop! Stop! Stop! WRONG. BAD.

Image for post
Image for post
Photo by Fernando @cferdo on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Global variables are defined outside of functions, methods, closures or types. That is, they are defined at the global scope.

Local variables are variables that are defined within a function, method or closure.

So why are there global variables when people on the Internet say that they should never be used????

We need to think about the alternatives that they recommend (if they even do), and make the best choices for our own situation.

This article is about making the right choices at the right time…

Prerequisites:

  • Coding in Swift Playgrounds (guide HERE) or create a single view application in Xcode (guide HERE)

The example

There is a counter variable in your app (perhaps in your AppDelegate) which can then be updated from anywhere in your App (perhaps when a user presses a button).

Image for post
Image for post

When the user updates counter from menuviewcontroller, traverses to detailviewcontroller and then updates the counter the counter will read 2.

The case for: Globals are a fast, easy to use technique

I would like to present a case for using global functions and variables. I’ll pick some reasons for their use, and explain this below:

Make small programs easy!

When we are making small demo programs, we might want to get coding and get the solution out in the world as fast as possible. We don’t want to get bogged down in arguments about architecture, rather we just want to get the code moving and make it work!

Somethings are available everywhere

You might want to set up a constant with a URL, and this is available in many parts of the progam. It doesn’t change so what is the harm?

Wrapping globals as Singletons isn’t the way to go

If you are spending time and effort in wrapping a global as a Singleton…what’s the point. Using a different tool and calling it something else to cover bad design of an App really doesn’t help anybody. If you’re using a global, use a global and be proud of what you’ve done!

Globals can save keystrokes

In order to type faster you can use Globals, because you can use them anywhere an use really small names.

The thought problem

To avoid having to think about where data should go, you can simply use a global. No thought required. Job done. Simples!

The case against: Globals are evil

The problem is that accessing a variable from anywhere in your application generates problems. Some cherry-picked examples of this are shown below

Thread safety

What if one counter is updated from multiple positions in your application of course this example is rather basic, more likely you would make requests from different threads which would reach the variable at (possibly) the same time.

This points to a lack of thread safety in using global variables — and let me tell you that this is a bad thing for your App as you are going to use threads whether you like it or not (specifically you will use the UI thread to update the user interface which should always respond to the user’s touch).

Coupling and Testing

Since we just have a simple variable (as suggested in App Delegate) it is difficult to claim that this is tightly coupled with anything (although global variables and functions often are).

However it is tricky to test the counter — as it is used by all sorts of functions within the App and can be changed in multiple places. Since this is true, how can we exclude the side-effects of all of the functions using the counter?

We should always (where possible) use a decoupled architecture that enables us to test our App and the functions adequately. It is possible to say that this is not truly possible in the case of global variables.

Even for small programs, it’s worth doing things right

Although it may seem persuasive to claim that it doesn’t matter whether we use globals for small programs, it is often those small programs that are the basis of larger Apps and programs. They can be worked upon and built as the very foundation of our work.

If it’s worth coding, it’s worth coding right!

Alternatives

Passing data along view controllers

You might choose to pass data from one view controller to another as an alternative to a global variable. Such a thing is called delegation, and does present the opportunity to use data where we need it.

However there is an issue, and that issue is are we using models properly in our architecture if we are simply passing variables from view controller to view controller. It is certainly unclear, although many developers will use massive view controller (sorry, MVC) that means this is their approach could be…perhaps not the best. In any case, you have options like MVVM which might give you flexability here.

The Singleton option

Essentially a class is wrapped around the global variable, and is known as a design pattern.

Is it an anti-pattern? You decide, but there is a guide on Singletons HERE which gives you an idea about how this can work.

The format for Singletons in Swift is as follows:

Class SingletonClass {
static let sharedInstance = SingletonClass
private init() {}
}

Conclusion

Stop and think about what you’re doing. Should you really be using a global variable for your particular use? You’re the only one who can decide — when programming you need to consider your current context and produce your software to the best of your ability. In other words, the choice is yours.

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store