Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
How can I optimize my code using enum-switch when return values are similar in most cases?

I have an enum and a switch with all cases on it, and I am using this switch inside a custom function, in most cases of switch I am returning same value, I would like to optimize my code for less and cleaner code as possible. With keeping and using Enum and switch.

enum Test {
    case a, b, c, d, e, f, g, h, i
}


func testFunction(value: Test) -> Int {
    switch value {
    case .a: return 1
    case .b: return 1
    case .c: return 1
        
    case .d: return 2
    case .e: return 2
    case .f: return 2
        
    case .g: return 3
    case .h: return 3
    case .i: return 3
    }
}
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can write your enum like this:

enum Test {
    case a, b, c, d, e, f, g, h, I

    var value: Int {
     switch self {
      case .a, .b, .c: return 1
      case .d, .e, .f: return 2
      case .g, .h, .i: return 3
     }
    }
 }
over 4 years ago · Santiago Trujillo Denunciar

0

If your cases are in a sequence you could make your enum conform to Comparable and do

func testFunction(value: Test) -> Int {
    switch value {
    case .a...(.c): return 1
    case .d...(.f): return 2
    default: return 3
    }
}
over 4 years ago · Santiago Trujillo Denunciar

0

Use comma:

func testFunction(value: Test) -> Int {
    switch value {
    case .a, .b, .c: return 1
        
    case .d, .e, .f: return 2
        
    case .g, .h, .i: return 3
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda