Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a singleton class in swift? [duplicate]

I need to create a singleton class in Swift. Can anyone help me with the code? I already know that singleton classes are very helpful in creating generic code.

like image 884
A_Curious_developer Avatar asked Jul 30 '15 07:07

A_Curious_developer


People also ask

What is Singleton in Swift?

In this tutorial, we will learn about Swift Singleton with the help of examples. In Swift, Singleton is a design pattern that ensures a class can have only one object. Such a class is called singleton class. 1. Create a private initializer

What are singletons in Android and how to use them?

Singletons can be very helpful if you need one instance of a class present throughout your entire app. With the increased RAM inside of our devices, singletons can help make our code more organized without having to worry about memory issues and crashes. To create a singleton, we must create an instance of the class inside of the class itself.

What is a singleton class?

Such a class is called singleton class. 1. Create a private initializer An initializer allows us to instantiate an object of a class. And, making the initializer of a class restricts the object creation of the class from outside of the class. Here, the initializer of the FileManager class is private.

What is singleton design pattern in Java?

Singleton is a design pattern that is very popular in development. Most of the developers are using this design pattern. This is very simple, common and easy to use in your project. It initializes your class instance single time only with static property and it will share your class instance globally.


2 Answers

There are many ways to create a Singleton Class in Swift. I am sharing with you one of the ways to implement this.

Write below code in Singleton Class.

import UIKit

final class GlobalData: NSObject {
   static let sharedInstance = GlobalData()

   private override init() { }

   func foo() { }
}

To access Singleton Class referencefrom other class:

let glblData = GlobalData.sharedInstance

OR access method directly

GlobalData.sharedInstance.foo()

Now we can use glblData as a reference to your singleton Class.

like image 83
Alok Avatar answered Nov 15 '22 08:11

Alok


class Singleton  {
   static let sharedInstance = Singleton()
}
like image 22
phnmnn Avatar answered Nov 15 '22 08:11

phnmnn