How to get strings from enum

Asked by At

I am trying to organize a bunch of string parameters in a enum. That way I can exclude the possibility of typos.

enum CompassPoint: String {
case n = "North"
case s = "South"
case e = "East"
case w = "West"
}

If I do it like this I need to use .rawValue to access the string. That is pretty ugly.

If I do it like this:

enum CompassPointAlt: String {
case n
case s
case e
case w

  var str: String {
    switch self {
    case .n: return "North"
    case .s: return "South"
    case .e: return "East"
    case .w: return "West"
    }
  }
}

I have to use the .str property to get the value. Which is visually more explicit, but the declaration is cumbersome.

There has to be a better way. Does anyone have a tipp for me? Thanks

2 Answers

1
Joakim Danielson On Best Solutions

You can use static in combination with enum if you are mostly interested in using the enum for constants

enum CompassPoint {
    static let n = "Nort"
    static let s = "South"
    static let e = "East"
    static let w = "West"
}
2
rpecka On

You could pull off some variation of the following:

import Foundation

enum Test: String, CustomStringConvertible {
    case n = "North"
    case s = "South"
    case e = "East"
    case w = "West"

    var description: String {
        return self.rawValue
    }
}

print("Enum: \(Test.n)") // Prints: Enum: North

CustomStringConvertible lets you run the code in the description variable without explicitly referencing it when you want to convert to a string. If you dont need the enums to have custom associated values like Hi and Bye above and you are cool with having the name of the type be what prints, then you can get as small as this:

import Foundation

enum TestSmall {
     case North
     case South
}

print("Enum: \(TestSmall.North)") // prints: Enum: North