Swift - Enumerations Associated Values

Introduction

To store a particular value or values associated with a particular member of an enumeration.

Consider the following code snippets:

enum InputType: String {
   case Keyboard = "Keyboard"
   case ThreeG = "3G"
}

enum InputDeviceType {
   case Phone  (InputType, String)
   case Tablet (String)
}

The first enumeration, InputType , represents the type of network to which a phone can connect.

The second enumeration, InputDeviceType , represents two types of devices: Phone or Tablet.

To use the preceding enumerations declared, take a look at the following code snippet:

var device1 = InputDeviceType.Phone(InputType.Keyboard, "iPhone 5S")
var device2 = InputDeviceType.Tablet("iPad Air")

For device1 , its type is a phone and you store the associated information (network type and model name) with it.

For device2 , its type is a tablet and you store its model name with it.

You can use a Switch statement to extract the associated value of an enumeration:

Demo

enum InputType: String {
   case Keyboard = "Keyboard"
   case ThreeG = "3G"
}

enum InputDeviceType {/*from   w w w.  j av a  2  s . c o m*/
   case Phone  (InputType, String)
   case Tablet (String)
}

var device1 = InputDeviceType.Phone(InputType.Keyboard, "iPhone 5S")
var device2 = InputDeviceType.Tablet("iPad Air")

switch device1 {
   case .Phone(let InputType, let model):
       print("\(InputType.rawValue) - \(model)")
   case .Tablet (let model):
       print("\(model)")
}

Result

Related Topic