As others have pointed out, Swift offers a simpler way to create singletons.
As an example: let's say we have a class called Model
, and we want to have a single instance, visible throughout our app. All we need to write in the global scope is:
let modelSingleton = Model()
This will create an instance of the Model
class, visible everywhere, and that cannot be replaced by another instance (Hmmm, that's pretty much what one would expect from a singleton, isn't it?).
Now, this way of doing would, on the other hand, still allow you to create other Model
instances, apart from the singleton. While this departs from the official definition of singletons in other languages, this approach would have the interesting advantage of allowing the creation of other instances for testing purposes (singletons have bad press in the unit testing world :) ).
Swift will soon offer everything needed to create real Singleton<T>
classes (it's hard now because class vars aren't allowed yet). But that being said, the approach described above will probably be more than enough for many Swift programmers.