Swift Global Variables

Generally, global variables are bad.  Some problems include tight coupling, that is your classes are now dependent on each other in ways that they shouldn’t be, namespace confusion – you might want to use the same name in a variable in 3,234th function, but you forgot that you have a global variable using that same name, and testing issues. http://c2.com/cgi/wiki?GlobalVariablesAreBad

However, I needed to temporarily use one in order to test push notifications, since the debugger is wonky with Amazon’s current push framework.  So it’s pretty easy.  Just place the variable outside of the class:

import UIKit

var globalVariable: String = ""

class MyRandomClass: NSObject {


The variable needs to be initialized.  People also recommend using structs for greater utility:

import UIKit

struct MyGlobalVariable {

    var wordVariable: String = ""

    var numberVariable: Int = 0


You can use the same struct device for global constants (just changing the var to a let).




Apple Docs on Global Variables

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>