iOS Swift Programming Patterns: Singleton

What is Singleton Pattern?

The Singleton pattern is class which initiated once itself and give global access to this created instance. As it has a unique instance, class variables and methods are shared in entire application/namespace. To understand better let's check where we can use this pattern.

Where we can use Singleton Pattern?

  • Accessing to common global variables, properties and definitions.
  • Accessing to common utility functions, methods


Example Singleton Class - Theory

The example above is base structure of a Singleton Pattern in Swift. "let" in Swift, create a constant variable of the class instance once. In this way we have weak variable, it means variable will be created once it's requested by any where in the project and will keep its value/functionality.

The example below is a real world example which show how to use Singleton to have a global access. In this example finding UIColor by hexadecimal value like 0xFFCC99. As this a very common func/method that we might need to access from any of our class in the project we construct as Singleton Pattern.

Example Singleton Class - Practice

This a partial code that I'm using in all my projects. You can improve by adding many similar functionality. Like this you will have a reusable  powerful class in your library.


Other Methods To Create Singleton:


Published on: 2015/11/28

Leave a Reply

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram