How to iterate string enum values?

bauss jacobbauss at gmail.com
Mon Dec 23 20:26:47 UTC 2024


On Monday, 23 December 2024 at 20:20:02 UTC, Anton Pastukhov 
wrote:
> I'm stuck on a simple problem.
> There is this string enum of MIME types:
>
> ```d
> enum BodyType: string {
>     PlainText = "text/plain",
>     JSON = "apllication/json",
>     FormUrlencoded = "application/x-www-form-urlencoded",
>     Multipart = "multipart/form-data",
>     Other = "Other",
>     None = "None"
> }
> ```
>
> Q: how can I iterate its values? With keys it's relatively easy:
>
> ```d
> auto keys = [EnumMembers!BodyType]
>     .map!(el => to!string(el))
>     .array;
>
> ```
> With values, though, I'm kinda stuck. Reading Ali's book and 
> https://dlang.org/spec/enum.html did not bring enlightening

Simply cast el to a string instead of using std.conv.to, that way 
you retrieve the values.

```
auto values = [EnumMembers!BodyType]
     .map!(el => cast(string)el)
     .array;
```


More information about the Digitalmars-d-learn mailing list