Current version of Swift does not support class variables. We have to wait until 1.2 version to be available with iOS 8.3.
Until then, how can I implement a singleton pattern in the Swift language.
My first idea would be something like:
But in current Swift version, the langage does not support the
this will be supported in version 1.2
But you can define a class variable in a structure using the
You can write something like the following:
Singleton of a class instance
You can easily implement a singleton object on top of stuctures.
Just make sure that the
init function is not public.
Using a module global variable
Next option would be to rely on the behavior of global variables: any global variable is lazily initialized
lazykeyword is not necessary as this is the default behavior.
Object won’t be initialized until it is used for the first time.
So you could write something like this:
As the global is a lazy variable, it won’t be created until the first call to
Note that this example won’t work in a playground as the sequential evaluation do not
allow to know the
GlobalSingleton class before the class is really created.
So declaration of the global
theInstance cannot be done in a playground.
Of course you must be careful when using the singleton pattern. This is not the best pattern to use, as this is roughly a global variable in your project.