I'm trying to "build" a few "spaceships" in my code. I'm feeling it's a good idea to enumerate all the spaceships and use that as a subscript to build and use an array that holds the spaceships' properties. After researching Stack Overflow and other places, I found a solution that works, but I'm feeling it's not very elegant and I'm probably not making good use of the Swift language. I'm also unhappy with having to define the name (string) of the spaceship again (and not using the enum case for that).
Do I miss the obvious cleaner solution? Any suggestions for a better solution?
enum SpaceshipName: Int, CaseIterable {
case Orion
case Vega
case Gemini
}
struct SpaceshipProperties {
var name: String = "TBD"
var fuel: Int = 0
var speed: Int = 0
}
// Initialize the spaceships:
var spaceShips = [SpaceshipProperties]()
for s in SpaceshipName.allCases {
spaceShips.append(SpaceshipProperties())
}
// Now start using the spaceships:
spaceShips[SpaceshipName.Orion.rawValue].name = "Orion"
spaceShips[SpaceshipName.Orion.rawValue].fuel = 100
spaceShips[SpaceshipName.Gemini.rawValue].speed = 2200
// ... and so forth
// Ultimately, I want to iterate through the spaceships in the following manner:
for s in SpaceshipName.allCases {
// Perform calculations with all the spaceships here, for example:
let newSpeed = spaceShips[s.rawValue].speed + 10
spaceShips[s.rawValue].speed = newSpeed
}
```