Enum

Enums, short for enumerations, are a class of types that can store one of a fixed set of named options. For example, the Text.Alignment enum can be either Left, Center, Right or Justify.

Text.Alignment alignment = Text.Alignment.Center

Enum type names are always associated with the element in which they are defined. However, while the "Alignment" enum shown previously was defined in the Text element but you can use it anywhere in your prototype.

You can declare new enums in your own elements. For example, you can define a "State" enum inside your ListEntry element as follows:

From ListEntry
Item {
    enum State {
        case Collapsed
        case Expanded
    }

    property State state: State.Expanded
}

When working within the element that defines the enum, you can simply use the short name "State". If you use the enum from another element, you must qualify its name, just like with the previous Text.Alignment example.

ListEntry.State state = ListEntry.State.Collapsed

You can test the value of an enum using the regular equality operators like this:

if state == ListEntry.State.Expanded {
    // state is Expanded
}

Convenience features

As the qualified names of enum values can be quite long, Zing includes some syntactic sugar to make using them easier.

Each enum value also has automatic, read-only "is" properties that allow you to quickly test its state. The following example is equivalent to explicitly comparing against ListEntry.State.Expanded.

if state.isExpanded {
    // state is Expanded
}

In most assignments and comparisons, Zing can also infer the fully qualified name from the short name by using the special "." contextual operator. Using contextual names behaves exactly the same as using the fully qualified name, but can save you some typing and improve the readability of your code.

root.state = .Collapsed // state is now Collapsed

Conversions

You can convert enums to strings, and strings to enums using a cast.

// Convert enum to string
var collapsed = ListEntry.State.Collapsed
String string = String(collapsed) // "ListEntry.State.Collapsed"

// Convert string to enum
ListEntry.State expanded = ListEntry.State("Collapsed")

Conversion from string to enum allows the string name to be qualified, so "State.Collapsed" and "ListEntry.State.Collapsed" will also work.