Home > Software design >  Confused by the usage of a class or a struct as container for static variables (Swift)
Confused by the usage of a class or a struct as container for static variables (Swift)

Time:09-22

In my app I currently use a separate class to store a bunch of static variables that I want to access from anywhere at anytime.

class Sounds {
    static var soundInitial : Sound!
    static var soundThunder : Sound!
    static var soundWind    : Sound!
    // etc... (about 50 more)
}

This Sounds class is never being used as an instance, but figures as a container for all the sound-effects (which are of type Sound - which is a separate class)

I initialize all the sound-effects from the Main View Controller during viewDidLoad:

let urlPath1 = Bundle.main.url(forResource: "art.scnassets/sounds/my_sound_file", withExtension: "mp3")
Sounds.soundInitial = Sound(url: urlPath1!, volume: 1.0)
// etc...

Then I can use it at any given time like so:

Sounds.soundInitial.play(numberOfLoops: -1) // endless looping

My very basic question as a not-yet-so-well-experienced-programmer:

Is there a more common approach or better way to store all my sound variables centrally together? (I don't want to define them in View Controller, because this would give me too much variables there...)

I found out, that I could use a struct to achieve the same. But would this be a better approach?

Is there a special Container Object in Swift designed for such purposes?

CodePudding user response:

What you're doing is clumping global constants into a namespace.

Is there a special Container Object in Swift designed for such purposes?

Yes, a caseless enum is the conventional way to do this, as it is the most lightweight and cannot be accidentally instantiated; it is "pure" namespace.

If you watch some Apple videos you'll see that's how they do it. Personally I used to recommend a struct but I've switched to using enums for the reason given.

  • Related