Swift - Using Enumeration in Switch Statements

Introduction

Enumerations are often used in Switch statements.

The following code snippet checks the value of codeColor and outputs the respective statement:


enum MyColor {
      case Black
      case White
      case Red
      case Green
      case Yellow
}
codeColor = MyColor.Yellow

switch codeColor {
    case MyColor.Black:
        print("Black")
    case MyColor.White:
        print("White")
    case MyColor.Red:
        print("Red")
    case MyColor.Green:
        print("Green")
    case MyColor.Yellow:
        print("Yellow")
}

Because the type of codeColor which is MyColor is already known, Swift allows you to specify only the enumeration members and omit the name:

switch codeColor {
    case  .Black :
        print("Black")
    case  .White :
        print("White")
    case  .Red :
        print("Red")
    case  .Green :
        print("Green")
    case  .Yellow :
        print("Yellow")
}

Related Topic