This article in Swift's documentation discusses creating a singleton with a class. I suspect it mentions only using classes because the topic is about Cocoa design patterns.
I wonder, in general, what are the pros and cons of using enums and structs vs. classes in creating singletons?
Lantua
2
One down side I can see on value types is that you can accidentally un-singleton them:
var a = Singleton.shared
a.mutate() // Oops
Wouldn't the new instance after mutation replace the original instance, so it remains a singleton?
Lantua
4
If you're using value types, mutating a won't be doing anything to Singleton.shared.
lukasa
(Cory Benfield)
5
Correct: value types conceptually cannot be singletons because they are never shared.
1 Like
Diggory
(Diggory)
6
If I’m modelling a real world object that obviously cannot be copied (e.g. electrical relay attached to a raspberry pi) then I make it a class singleton because references make more sense in this case.