Lokang 

Swift and MySQL

Enumeration

In Swift, enumerations (often called enums) are a powerful way to define a common type for a group of related values, enabling you to work with those values in a type-safe way within your code. Enumerations in Swift have more capabilities compared to enums in languages like C and Objective-C.

Defining Enumerations

Here's a simple example:

enum CompassPoint {
   case north
   case south
   case east
   case west
}

You can also define multiple cases in a single line, separated by commas:

enum Planet {
   case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

Using Enumerations

To work with enumerations, you can use a switch statement for matching enumeration values:

var direction = CompassPoint.north
switch direction {
case .north:
   print("Lots of planets have a north")
case .south:
   print("Watch out for penguins")
case .east:
   print("Where the sun rises")
case .west:
   print("Where the skies are blue")
}

Associated Values

Enumerations in Swift can also have associated values, which means you can store additional custom information along with each case.

enum Barcode {
   case upc(Int, Int, Int, Int)
   case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
   print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
   print("QR code: \(productCode).")
}

Raw Values

Enums can have raw values, which must be unique within the enum's scope. These can be useful for encoding an enum's state to a primitive data type.

enum ASCIIControlCharacter: Character {
   case tab = "\t"
   case lineFeed = "\n"
   case carriageReturn = "\r"
}

You can also use implicit assignment for enums with integer or string raw types:

enum Planet: Int {
   case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
let earthsOrder = Planet.earth.rawValue  // earthsOrder is 3

Initializing from Raw Values

If you have a raw value, you can find the corresponding enum case using the enum's initializer.

let possiblePlanet = Planet(rawValue: 3)  // possiblePlanet is of type Planet? and equals Planet.earth

Recursive Enumerations

Swift allows for recursive enumerations, which are enumerations that have another instance of the enumeration as the associated value for one or more of the enumeration cases. You indicate that an enumeration case is recursive by writing indirect before it.

indirect enum ArithmeticExpression {
   case number(Int)
   case addition(ArithmeticExpression, ArithmeticExpression)
   case multiplication(ArithmeticExpression, ArithmeticExpression)
}

Enumerations in Swift are much more flexible than in many other languages, allowing for a wide range of applications in modeling data and behavior. They are commonly used in switch statements, data models, and protocol definitions.