GNOME Bugzilla – Bug 624691
Improve Enum: add foreach capabilites
Last modified: 2018-05-22 13:42:28 UTC
It would be great if it were posible to use foreach statement in Enum blocks, as seen in this example: public enum MyEnum { A, B, C, D, E } bool lookup_whatever() { foreach(MyEnum elem in MyEnum) { if(matrix[elem]==5) return true; } }
Agreed, that would be handy in some situations. Obviously there is a simple workaround by adding a MAX_VALUE and iterating over an int, still foreach support would be nice as syntatic sugar.
Created attachment 207054 [details] [review] Proposed Patch With this patch valac generates a ".all_values" constant to enums. It can be used with foreach like this: foreach (Enum e in Enum.all_values) { stdout.printf ("%s\n", e.to_string ()); } If one wants support for "foreach(Enum e in Enum)" this, or a similar method is needed to avoid the gap problem (e.g. enum Example { FOO = 1, BAR = 3 };).
So long as the Vala enum is not defined with the CCode detail has_type_id = false then Vala uses GLib's GEnumClass. So to print a list of values and code names in an enum : enum Test { ONE, THREE = 3; } void main () { foreach (EnumValue value in ((EnumClass) typeof (Test).class_ref()).values) { print (@"$(value.value) - $(value.value_name)\n"); } } There are two points to consider: 1. Syntactic sugar in Vala to avoid the complex introspection calls 2. The handling of "C" like enums, i.e. defined as has_type_id = false, that applies to both Vala code and bindings. "C" like enums do already have a .to_string method when the enum is defined in a Vala source and not externally by a C library, so special code to generate an iterator to use with foreach may be ok. With an externally defined enum then it would have to be an error from Vala. The same should also apply to Flags. For reference see: https://developer.gnome.org/gobject/stable/gobject-Enumeration-and-Flag-Types.html#g-enum-get-value
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/vala/issues/123.