Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Swift enums have multiple raw values?

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 switched on self to look up the appropriate value?

like image 309
Robert Atkins Avatar asked Dec 30 '14 14:12

Robert Atkins


1 Answers

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.

like image 59
Antonio Avatar answered Oct 19 '22 08:10

Antonio