Enumeraciones en Swift: raw values, associated values y pattern matching

Un caso puede llevar datos de cualquier tipo, distintos por caso:

enum Resultado {
    case exito(valor: Int)
    case fallo(mensaje: String)
    case pendiente
}

let r = Resultado.exito(valor: 42)
switch r {
case .exito(let v):   print("OK: (v)")
case .fallo(let m):   print("Error: (m)")
case .pendiente:      print("Esperando")
}
// OK: 42

Métodos en enums

enum Planeta: Int {
    case mercurio=1, venus, tierra, marte

    var esHabitable: Bool { self == .tierra }

    func descripcion() -> String {
        "Planeta (rawValue): (self)"
    }
}

print(Planeta.tierra.esHabitable)       // true
print(Planeta.marte.descripcion())      // Planeta 4: marte

Enums indirectos (recursivos)

indirect enum Expresion {
    case numero(Int)
    case suma(Expresion, Expresion)
    case producto(Expresion, Expresion)
}

func evaluar(_ e: Expresion) -> Int {
    switch e {
    case .numero(let n):         return n
    case .suma(let a, let b):    return evaluar(a) + evaluar(b)
    case .producto(let a, let b): return evaluar(a) * evaluar(b)
    }
}

let expr = Expresion.suma(.numero(3), .producto(.numero(4), .numero(5)))
print(evaluar(expr))  // 23

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP