Swift - Enumeration Raw Values

Introduction

You can associate a value with the members of an enumeration.

For example, to store the value of codeColor to a file as a string.

enum MyColor : String  {
    case Black = "Black"
    case White   = "White"
    case Red  = "Red"
    case Green  = "Green"
    case Yellow  = "Yellow"
}

The String in the preceding code snippet is known as the raw type.

Each raw value must be unique within the enumeration.

To obtain the value of an enumeration, use the rawValue property of the enumeration instance:

Demo

enum MyColor : String  {
    case Black = "Black"
    case White   = "White"
    case Red  = "Red"
    case Green  = "Green"
    case Yellow  = "Yellow"
}


var codeColor:MyColor

codeColor = MyColor.Yellow/*from ww  w . j  av  a2  s .c om*/

var c = codeColor.rawValue

print(c)  //prints out "Yellow"

Result

The rawValue property will return the value that you have assigned to each member of the enumeration.

Related Topic