Swift - Data Type Enumeration Functions

Introduction

You can define a function within an enumeration.

The following code adds a function named info to the InputDeviceType enumeration:

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


enum InputDeviceType {
   case Phone (InputType, String)
   case Tablet(String)
    var info: String {
        switch (self) {
            case let .Phone  (InputType, model):
                return "\(InputType.rawValue) - \(model)"
            case let .Tablet (model) :
                return "\(model)"
        }
    }
}

Here, the info() function returns a string.

It checks the member that is currently selected using the self keyword and returns either a string containing the network type and model for phone or simply the model for tablet.

To use the function, simply call it with the enumeration instance, as shown here:

Demo

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


enum InputDeviceType {/*ww w.j a  v a  2  s  . c om*/
   case Phone (InputType, String)
   case Tablet(String)
    var info: String {
        switch (self) {
            case let .Phone  (InputType, model):
                return "\(InputType.rawValue) - \(model)"
            case let .Tablet (model) :
                return "\(model)"
        }
    }
}

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

print(device1.info )  //Keyboard - iPhone 5S
print(device2.info )  //iPad Air

Result

Related Topic