I'd like to generate a Dictionary dynamically, but I tried to do it as a struct property unsuccessfully, where I got the error Value of type 'SpaceAge' has no subscripts in self["on\(planet)"].
Regarding the subscript, I'll need to have the property onPlanet accessible, as in myAge.onMars or myAge.onNeptune since I have unit tests that expect to compute the values. Are the subscripts ok for that?
Example:
func testAgeInMercuryYears() {
let age = SpaceAge(2_134_835_688)
XCTAssertEqual(67.65, age.onEarth, accuracy: 0.01)
XCTAssertEqual(280.88, age.onMercury, accuracy: 0.01)
}
I would change the tests to use age[on: .earth], etc.
If you must have properties, you can implement dynamic member lookup, but that is a much more advanced topic and almost certainly overkill here.
Or you could manually implement var onEarth: Double { self[on: .earth] }. But again, it’s probably better not to have onEarth at all, and just write age[on: .earth].
Doing it the way I describe makes it easy to introduce new planets:
let krypton = Planet(name: "Krypton", orbitalPeriod: 1.37)
print(myAge[on: krypton])