Home > Blockchain >  How can I optimize my code using enum-switch when return values are similar in most cases?
How can I optimize my code using enum-switch when return values are similar in most cases?

Time:12-09

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
    }
}

CodePudding user response:

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
     }
    }
 }

CodePudding user response:

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
    }
}

CodePudding user response:

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
    }
}
  • Related