- Swift Tutorial
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Variables
- Swift - Constants
- Swift - Literals
- Swift - Comments
- Swift Operators
- Swift - Operators
- Swift - Arithmetic Operators
- Swift - Comparison Operators
- Swift - Logical Operators
- Swift - Assignment Operators
- Swift - Bitwise Operators
- Swift - Misc Operators
- Swift Advanced Operators
- Swift - Operator Overloading
- Swift - Arithmetic Overflow Operators
- Swift - Identity Operators
- Swift - Range Operators
- Swift Data Types
- Swift - Data Types
- Swift - Integers
- Swift - Floating-Point Numbers
- Swift - Double
- Swift - Boolean
- Swift - Strings
- Swift - Characters
- Swift - Type Aliases
- Swift - Optionals
- Swift - Tuples
- Swift - Assertions and Precondition
- Swift Control Flow
- Swift - Decision Making
- Swift - if statement
- Swift - if...else if...else Statement
- Swift - if-else Statement
- Swift - nested if statements
- Swift - switch statement
- Swift - Loops
- Swift - for in loop
- Swift - While loop
- Swift - repeat...while loop
- Swift - continue statement
- Swift - break statement
- Swift - fall through statement
- Swift Collections
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift Functions
- Swift - Functions
- Swift - Nested Functions
- Swift - Function Overloading
- Swift - Recursion
- Swift - Higher-Order Functions
- Swift Closures
- Swift - Closures
- Swift-Escaping and Non-escaping closure
- Swift - Auto Closures
- Swift OOps
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift-Overriding
- Swift - Initialization
- Swift - Deinitialization
- Swift Advanced
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Error handling
- Swift - Concurrency
- Swift - Type Casting
- Swift - Nested Types
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift - Function vs Method
- Swift - SwiftyJSON
- Swift - Singleton class
- Swift Random Numbers
- Swift Opaque and Boxed Type
- Swift Useful Resources
- Swift - Compile Online
- Swift - Quick Guide
- Swift - Useful Resources
- Swift - Discussion
Swift - Singleton Class
A Singleton Class is a special class which have only one object and will make sure that your application or program uses that object. If you try to create another variable of singleton class you will get an error. Singleton class is easy to use but it has a major drawback which is global access, which means you can access singleton class globally by sharing the instance of the class.
Which makes it hard to maintain, can lead to concurrency issues, etc. So to avoid excess use of singleton object we use dependency injection. Dependency injection passes the singleton object to the object where it is required.
If a class depends upon the singleton and they are present in different contexts, then you have to import a singleton into that context without importing the class cannot access the singleton.
Syntax
Following is the syntax of the Singleton Class −
class Name{ // body }
Creating and Accessing Singleton Class
We can create a singleton class just like the normal class using the “class” keyword but with some different rules and they are −
A singleton class should have a private initializer.
A singleton class should have a static-type object.
Private Initializer
This private initializer prevents the object creation from outside the class. If you try to create an object outside the class you will get an error. To create a private initializer we will use a “private” keyword.
Syntax
Following is the syntax for private initializer −
private init(){}
Example
Swift program to create a singleton class with a private initializer.
import Foundation // Outer class class SingletonClass{ // Creating a private initializer private init(){} func show(){ print("Hello") } } // Creating object outside the class // We will get an error let myObject = SingletonClass() myObject.show()
Output
It will produce the following output −
main.swift:16:16: error: 'SingletonClass' initializer is inaccessible due to 'private' protection level let myObject = SingletonClass()
Here the private protection level prevents us from creating an object outside the class. So to overcome this error we have to create an object inside the class.
Static Object
If we have a static object inside the single class we can easily access the object by using the class name. To create a static object we use the “Static” keyword.
Syntax
Following is the syntax for static objects −
static let objectName = className()
Following is the syntax for accessing static objects −
let variableName = className.objectName
Example
Swift program to create a singleton class with an object.
import Foundation // Singleton class class SingletonClass{ // Creating object outside the class static let myObject = SingletonClass() // Creating a private initializer private init(){} // Method func show(){ print("Hello I am Singleton Class") } } // Accessing the object let ob = SingletonClass.myObject // Accessing the method ob.show()
Output
It will produce the following output −
Hello I am Singleton Class
Singleton Class | Normal Class |
---|---|
It have only one instance throughout the lifetime of the program. | It can have multiple instances. |
It does not allows you to create instances of the class. | It allows you to directly create instances of the class using its initializer. |
You can access the instance with the help of shared properties and methods that provide global access to the object. | You can directly access the instances. |
It is less flexible in terms of creating objects and can use tight coupling between different parts of the code. | It is more flexible in terms of creating objects and can allow loose coupling between different parts of the code. |
Testing singleton class is difficult because of global state and dependencies. | Testing normal classes is much more easier. |