'What's the difference between Struct based and Class based singletons?
Are the two approaches the same or are there major differences/pitfalls 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") }
}
Solution 1:[1]
That depends on what you want to achieve and how you want to use your structure based on differences between class and struct. Most common thing that you will see is using class with singleton object.
Singletons are pretty much the same, they are only created once, but you will get different behaviors from the class and from struct because:
- Classes are reference types, while structs are value types
- Structs are used to define simple structures
- Structs can't be inherited
There are several more differences but you get the idea from this.
Solution 2:[2]
As already mentioned in another answer, classes and structs have different properties. Most importantly, classes have reference semantics whereas structs have value semantics.
Nonetheless, a global variable (or a static property) introduces reference semantics, even if it's defined in a struct, suggesting that you can indeed implement a (mutable) singleton with a struct.
The problem illustrated by Sergey Kalinichenko is that assigning the value of a struct to another variable will create a copy rather than a reference (remember, structs have value semantics). So the mutations on the copy won't apply to the original value. Should you mutate the static property of your struct directly, your singleton would indeed be modified.
struct Singleton {
private init() {}
var state = 5
static var sharedInstance = MyStructSingleton()
}
Singleton.sharedInstance.state = 10
print(Singleton.sharedInstance.state) // 10
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Said Sikira |
| Solution 2 | Alvae |
