Sobes.tech
Junior

What are the cases in enumeration (enum)?

sobes.tech AI

Answer from AI

The following cases exist in enumeration:

  • Raw-value cases: Associated with a specific value of the base type (Int, String, Character, Float). Values are explicitly set or automatically generated for Int and String.

    enum CompassPoint: String {
        case north = "N"
        case south //rawValue not specified, defaults to "south"
        case east = "E"
        case west = "W"
    }
    let direction = CompassPoint.north.rawValue // "N"
    
  • Associated-value cases: Can have associated values of any types, providing additional context or data. They do not have a raw value or base type.

    enum Barcode {
        case upc(Int, Int, Int, Int)
        case qrCode(String)
    }
    let productBarcode = Barcode.upc(8, 85909, 51226, 3)
    
  • Recursive cases: Marked with the indirect keyword and allow the enumeration to have associated values of the same enumeration type. Used for representing recursive data structures like trees.

    indirect enum ArithmeticExpression {
        case number(Int)
        case addition(ArithmeticExpression, ArithmeticExpression)
        case multiplication(ArithmeticExpression, ArithmeticExpression)
    }
    let five = ArithmeticExpression.number(5)
    let four = ArithmeticExpression.number(4)
    let sum = ArithmeticExpression.addition(five, four)
    let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))