0

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?

ZAY
  • 3,882
  • 2
  • 13
  • 21
  • 2
    If you use a class or struct for this then you should declare a private init so no instances can be created, `private init() {}`. But a more common approach is to use an enum for your static variables (just replace the word “class” with “enum” in your code above). – Joakim Danielson Sep 18 '21 at 09:45
  • This works like charm. So easy. Perfect comment! – ZAY Sep 18 '21 at 10:24
  • 2
    Related: [Swift constants: Struct or Enum](https://stackoverflow.com/q/38585344/1187415) – Martin R Sep 18 '21 at 10:25

1 Answers1

3

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141