Douglas Silva
Douglas Silva

Reputation: 145

Get value of enum type in swift

I'm trying to get a default value for the enum so I can use it as a param. This code isn't working, but I'd like to get something like:

print("Param: \(Params.RCLoss.description)")

and the output should be:

Param: RC_LOSS_MAN

Here is the code:

enum Params {
  enum RCLoss: Int32, CustomStringConvertible {
    case disable = 0
    case enable = 1

    var description: String {
        return "RC_LOSS_MAN"
    }
  } 
}

I want to be able to pass this:

set(parameterType: Params.RCLoss.description, parameterValue: Params.RCLoss.enable)

which should correspond to these values being set:

set(parameterType: "RC_LOSS_MAN", parameterValue: 0)

Upvotes: 0

Views: 430

Answers (2)

Sulthan
Sulthan

Reputation: 130072

It seems you want just

enum rcLoss: Int32 {
  case disable = 0
  case enable = 1 

  static var description: String {
    return "RC_LOSS_MAN"
  }
}

rcLoss is a type, description has to be static for you to be able to call rcLoss.description. And that means you cannot use CustomStringConvertible. You would use CustomStringConvertible to convert enum values to a String.

Upvotes: 1

keji
keji

Reputation: 5990

From Swift Book - Enumerations:

You access the raw value of an enumeration case with its rawValue property.

set(parameterType: Params.rcLoss.description, parameterValue: Params.rcLoss.enable.rawValue)

If you can though I would use the enumeration as the type of the formal parameter so that someone can't pass an invalid value to that function. Also I'm assuming that there is a reason you have nested an enum inside of an otherwise empty enum...

Upvotes: 0

Related Questions