Swift - Data Type Enumerations

Introduction

An enumeration is a first-class type.

It defines list of possible values.

Enumerations are defined via enum keyword.

Once you've got your enumeration, you can use it like any other variable in Swift:

You can also change it to a different value of the same type:


enum Direction { 
    case North 
    case South 
    case East 
} 

var nextiPad = Direction.South 
nextiPad =  .North 

Here we didn't fully specify the enumeration name.

In Swift you can use the shorthand form of an enumeration to refer to it.

You cannot use it for the first declaration, but all subsequent ones work fine.

You can use a switch statement to match enumeration values:

Demo

enum Direction { 
    case North //  ww  w.ja v  a 2  s .  c o m
    case South 
    case East 
} 

var nextiPad = Direction.South 
nextiPad =  .North 

switch nextiPad { 
case  .North: 
    print("Too big!") 
case  .South: 
    print("Too small!") 
case  .East: 
    print("Just right!") 
}

Result

Swift enumerations don't automatically have a corresponding integer value.

The members of an enumeration are values themselves, and are of the type of that enumeration.

Related Topics

Exercise