-1

I have the following enum and it works. However, is there a way that I can simply change Int and make it String and then directly assign?

is not it the following to wordy ? Companies(rawValue: httpMethod.self.rawValue)! compared to Companies.stringValue

How could I call the following to get the String value?

public enum Companies: String {
  case oil = "OIL"
  case tech = "TECH"
  case government = "GOVERNMENT"
  case restaurant = "RESTAURANT"
}

The following works!

public enum Companies: Int {
  case oil
  case tech
  case government
  case restaurant

  var stringValue: String {
    switch self {
    case .oil:
      return "OIL"
    case .tech:
      return "TECH"
    case .government:
      return "GOVERNMENT"
    case .restaurant:
      return "RESTAURANT"
    }
  }
}

I could simply call Companies.stringValue

casillas
  • 16,351
  • 19
  • 115
  • 215
  • “But why the following does not work?“. It does work. In fact you can even remove the assignments and it still works. – matt Jun 19 '20 at 22:48
  • Sorry @matt, I have fixed my question. I apologize. – casillas Jun 19 '20 at 22:50
  • 1
    How about [this answer](https://stackoverflow.com/a/24707744/3791245): use `enum Companies: CustomStringConvertible` and add `var description: String` instead of `stringValue`. – Sean Skelly Jun 19 '20 at 23:05
  • I still don't see the point. Please provide a genuine use case. – matt Jun 19 '20 at 23:06
  • `enum Companies: String, CustomStringConvertible {` `case oil, tech, government, restaurant` `public var description: String { rawValue.uppercased() }` `}` – Leo Dabus Jun 20 '20 at 00:01

2 Answers2

2

please try this:

public enum Companies: String {
 case oil
 case tech
 case government
 case restaurant
 }
 let c = Companies.oil
 print(c.rawValue)
Moumen Alisawe
  • 2,498
  • 2
  • 12
  • 18
1

Add a calculated property to your enum

public enum Companies: Int {
    case oil
    case tech
    case government
    case restaurant

    var string: String {
        "\(self)".uppercased()
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52