Search code examples
iosswiftoopswiftuiglobal-variables

Swift - What is a better alternative to Global Variables?


Context

Hi there,
I like using global variables to call managers or services to handle certain code.
But I am getting code smells in my code analyser (SonarQube).

Question

Is there a big difference between form A and B? Or should I not be using either at all? I prefer form A, but I'd like to avoid / suppress / resolve code smells.

Form A

Some examples, what I prefer:

app.logout()
cameraManager.doSomething()
userDefaults.set(.example, true)
analytics.logEvent(.clicked_button)
popupManager.showPopup(message: "Hello world!")

The above can be achieved with:

var app = Global()

class Global {

}

Form B

An alternative would be:

class Global {
    private init() {}
    public static let app = Global()
}

The usage would then change to Global.app.logout()

Code Smells

Code smells say difficult to use because of the risk of name classes, difficult to track bugs, updated from anywhere, difficult to properly test classes

I partially agree with these points, but wouldn't the same count for Form B? If so, is there better approach other than what I've shown above?

I'd love to hear your insights!


Solution

  • The problem you are facing is that global variables, in and of themselves, are often considered a code smell.

    Essentially, you are saying "I like <code smell> but my code analyzer is flagging it as a code smell."

    Have you considered making your manager objects singletons? Consider the pattern Apple uses for things like UserDefaults (a class var standard that returns the shared UserDefaults object.)

    Edit:

    Rereading your question, I guess that's what you are suggesting in form B. That makes the static var a class variable of the class, and turns the object into a singleton. It's not quite the same thing as a global.