Singleton VS static(class) variables [closed]

2020-02-09 08:35发布

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

标签: ios swift macos
1条回答
Lonely孤独者°
2楼-- · 2020-02-09 09:12

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.

  • Create a class if you ever want to have multiple SomeManager instances.
  • A singleton can be good default instance but there may be edge cases where you want to have separate behavior (testing).
  • Dependency Injection... is big topic that is relevant if SomeManager is storing global state.

Static Variable

  • Always use when the someVariable is a constant.
  • Does not require extra storage for static var sharedManager = SomeManager(); you use only the memory which you actually need.
  • Slightly faster because you do not need to load sharedManager into memory then access it's member someVariable. You straight up access someVariable.

Bonus Tip:

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()
查看更多
登录 后发表回答