Swift - Data Type Using Enumerations


An enumeration is a user-defined type with a group of named constants.

The following code creates an enumeration containing all the valid colors.

enum MyColor {
      case Black
      case White
      case Red
      case Green
      case Yellow

The MyColor enumeration contains five cases also known as members: Black , White , Red , Green , and Yellow.

Each member is declared using the case keyword.

You can group the five separate cases into one single case, separated using commas ,

enum MyColor {
   case Black ,  White,  Red ,  Green,  Yellow

You can now declare a variable of this enumeration type:

var codeColor:MyColor

To assign a value to this variable, specify the enumeration name, followed by its member:

codeColor = MyColor.Yellow

In Swift, you need to specify the enumeration name followed by its member.

You can omit the enumeration name by simply specifying its member name:

codeColor = .Yellow

Related Topic