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
tl;dr
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.
Singleton Class (or struct) with variables
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.Static Variable
someVariable
is a constant.static var sharedManager = SomeManager()
; you use only the memory which you actually need.sharedManager
into memory then access it's membersomeVariable
. You straight up accesssomeVariable
.Bonus Tip:
In Option 2 you can create
SomeManager
even though it doesn't do anything. You can prevent this by turningSomeManager
into an enum with no cases.You can still do this:
but you can't do this