Home > Net >  How can I stop repeating code for accessing value of associated type enum?
How can I stop repeating code for accessing value of associated type enum?

Time:09-22

I want to access to value of my enum in case, I made a switch for getting access to value, but as you can see I am reaping my codes, how can i do this in better way?

enum TestEnum {
    case a(value: Int)
    case b(value: Int)
    case c(value: Int)
    
    var value: Int {
        switch self {
        case .a(let value):
            return value
        case .b(let value):
            return value
        case .c(let value):
            return value
        }
    }
}

CodePudding user response:

Maybe you could change the way your data is modeled

struct MyStruct {
  enum Kind {
    case one, two, three
  }
  
  let kind: Kind
  let value: Int
}

CodePudding user response:

 var value: Int {
    switch self {
    case .a(let value),
         .b(let value),
         .c(let value):
        return value
    }
}
  • Related