About Global variable for iOS Project
There are several ways to create "global" variables in Swift, and I will describe some of them.
1. Defining variables in AppDelegate
AppDelegate
seems like a logic place for some global variables. As you said you can create instance of logger or create instance of something else in AppDelegate
.
To create instance which will be used as a global variable go to the AppDelegate.swift
and create the variable like this:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
let myAppInstance = SomeClass()
...
}
Then, if you want to access myAppInstance
in any other part of the application you would write:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.myAppInstance.doSomething()
2. Creating singletons
Singletons are probably one of the most used design patters used through any Apple platform. They are present in almost any iOS API you are using when creating application, and they are commonly used to create global variables.
Essentially, singletons are lazy-loaded instances which are only created once. Let's look at the code example:
class MyDataStructure {
static var sharedInstance = MyDataStructure() // This is singleton
private init() {
}
}
We have created the class MyDataStructure
and the singleton instance named sharedInstance
. This is the most common name for the singletons since that singletons are shared instances through the app.
Note the use of the static
keyword when defining singleton. static
keyword tells the compiler to create sharedInstance
only the first time it is being accessed. Any other access to the sharedInstance
will just reuse instance that is created first time.
To use it you would just write:
MyDataStructure.sharedInstance