I want to associate two raw values to an enum instance (imagine an enum representing error types, I want Error.Teapot
to have an Int type property code
with value 418, and a String property set to I'm a teapot
.)
Note the difference between raw values and associated values here—I want all Teapot
instances to have a code
of 418, I don't want a unique associated value for each Teapot
instance.
Is there a better way than adding computed properties to the enum that switch
ed on self
to look up the appropriate value?
No, an enum cannot have multiple raw values - it has to be a single value, implementing the Equatable
protocol, and be literal-convertible as described in the documentation.
I think the best approach in your case is to use the error code as raw value, and a property backed by a prepopulated static dictionary with the error code as key and the text as value.