7

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.

Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
A_Curious_developer
  • 483
  • 1
  • 5
  • 12
  • It's duplicate here. http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift – Long Pham Jul 30 '15 at 07:54

3 Answers3

19

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.

Alok
  • 24,880
  • 6
  • 40
  • 67
  • 2
    It is also a good idea to override the init and make it private, ie: `priviate init() { }` so that another instance cannot be created. (You don't want the singleton itself and multiple instances) – micnguyen Aug 16 '18 at 06:37
  • 1
    What if someone writes let data = GlobalData() somewhere else in code?? This will create another instance of the class, hence violating singleton, we should make its constructor private to follow singleton. – Abuzar Amin Dec 17 '18 at 08:35
7
class Singleton  {
   static let sharedInstance = Singleton()
}
phnmnn
  • 12,813
  • 11
  • 47
  • 64
  • 1
    Singleton class required private constructor (init). So it means you can't create more object of class "Singleton" by doing let obj = Singleton(). you must need to private its constructor. – Vasucd Mar 11 '20 at 13:48
  • no its not singleton class, you can create an instance of Singleton class again. Singleton class means "Single instance of class throughout the whole application" – Nirav Hathi Jun 12 '20 at 04:12
4

You can create various Singleton. Below is the code for the simplest and most generic Singleton class:

class Singleton {
   static let sharedInstance = Singleton()
}
Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
  • 1
    These are old methods prior to Swift 1.2 - @phnmnn is the easiest (and less error prone) way to define singletons – Antonio Jul 30 '15 at 07:56
  • no its not singleton class, you can create an instance of Singleton class again. Singleton class means "Single instance of class throughout the whole application" – Nirav Hathi Jun 12 '20 at 04:13