Imagine we are making a game. The difficulty of this game can be changed in real-time (mid-game) and will be controllable at all times with three buttons that are always on screen.
The Swift type that represents this app "state" is:
enum CurrentDifficultyState {
case low
case medium
case max
}
Lets say we have put this code in the ViewController.
But... in our model... we have something like enemyController.swift that has a member function like generateEnemy(currentDifficulty: CurrentDifficultyState)
.
The "difficulty" of this enemy will depend on the state of this enum at the moment it spawns.
When we do it like this, though, XCode complains (from inside the file enemyController.swift) that there is no such type as "CurrentDifficultyState" presumably because it hasn't been defined inside the enemyController.swift file (it was written in the ViewController file).
So... what is the proper way to handle this? Where can we move this code to (or what keyword is it missing) so that it will be a global (static?) accepted type just like String
or Int
... accessible to all classes across the app?
What I ended up doing was creating a new swift file called "myGlobalTypes.swift" and putting the enum code in there.
This works!
But this seems like a trashy way to do it.
Could anyone enlighten me? Thank you!
PS - Please don't ask for more code... the "game" thing was just a hypothetical example to give some context to the question (which is general)... but I'm not experienced enough to ask the real question point-blank because I don't know all the relevant terms.
Just put your enum
at the top level scope in whatever file you want. For instance, put it inside a enemyController.swift file at the top level (outside the UIViewController
class)