What is the best practice in Swift?
Option 1:
class SomeManager {
static var sharedManager = SomeManager()
var someVariable: String?
}
and then
let something = SomeManager.sharedManager().someVariable
Option 2:
class SomeManager {
static var someVariable: String?
}
and then
let something = SomeManager.someVariable
Definitely the most common usage is that singleton is normal object that holds member variables. You can, for example, easily replace one object with another (with all other properties). Every class can have static variables but it does not deppend wheter it is singleton or not.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .
Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class.
Extensibility. It is not possible to inherit from a static class, while it is possible with singleton pattern if you want to allow it. So, anyone can inherit from a singleton class, override a method and replace the service.
Option 1 (class or struct) when you store mutable state because you need other instances.
Option 2 (scoped global variables) when you want to store static variables because it's faster and uses less memory.
Global state is generally considered a "bad thing". It's hard to think about, causes problems but is sometimes unavoidable.
SomeManager
instances. SomeManager
is storing global state.someVariable
is a constant.static var sharedManager = SomeManager()
; you use only the memory which you actually need.sharedManager
into memory then access it's member someVariable
. You straight up access someVariable
.In Option 2 you can create SomeManager
even though it doesn't do anything. You can prevent this by turning SomeManager
into an enum with no cases.
enum SomeManager {
static var someVariable: String?
}
You can still do this:
SomeManager.someVariable
but you can't do this
let manager = SomeManger()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With