Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!