What is the difference between Struct and Class based singles?

Are these two approaches the same or are there significant differences / traps to be aware of:

class MyClassSingleton {
  static let sharedInstance = MyClassSingleton()
  private init(){}

  func helloClass() { print("hello from class Singleton") }
}

struct MyStructSingleton {
  static let sharedInstance = MyStructSingleton()
  private init() {}

  func helloStruct() { print("hello from struct Singleton") }
}
+17
source share
2 answers

The main difference is that multi-user single-user mode works, while the structural mutable “singleton” does not. If you don't want to make your singleton immutable (which is rare), you should stick to the class.

Here's an illustration of how the volatile structural "singleton" doesn't work. Consider adding a mutable member stateto both singletones, for example:

class MyClassSingleton {
    static let sharedInstance = MyClassSingleton()
    private init(){}
    var state = 5
    func helloClass() { print("hello from class Singleton: \(state)") }
}

struct MyStructSingleton {
    static let sharedInstance = MyStructSingleton()
    private init() {}
    var state = 5
    func helloStruct() { print("hello from struct Singleton: \(state)") }
}

state a var, ; , .

let csi = MyClassSingleton.sharedInstance
csi.state = 42
MyClassSingleton.sharedInstance.helloClass()

42 , csi .

,

var ssi = MyStructSingleton.sharedInstance
ssi.state = 42
MyStructSingleton.sharedInstance.helloStruct()

5 , ssi sharedInstance, , , , .

+34

, class struct. , , - .

, , class struct, :

  • - , -

, .

+2

Source: https://habr.com/ru/post/1683155/


All Articles