In Swift, is it possible to convert a string to an enum?

Sure. Enums can have a raw value. To quote the docs:

Raw values can be strings, characters, or any of the integer or
floating-point number types

— Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l,

So you can use code like this:

enum StringEnum: String 
{
    case one   = "value one"
    case two   = "value two"
    case three = "value three"
}

let anEnum = StringEnum(rawValue: "value one")!

print("anEnum = \"\(anEnum.rawValue)\"")

Note: You don’t need to write = “one” etc. after each case. The default string values are the same as the case names so calling .rawValue will just return a string

EDIT

If you need the string value to contain things like spaces that are not valid as part of a case value then you need to explicitly set the string. So,

enum StringEnum: String 
{
  case one
  case two
  case three
}

let anEnum = StringEnum.one
print("anEnum = \"\(anEnum)\"")

gives

anEnum = “one”

But if you want case one to display “value one” you will need to provide the string values:

enum StringEnum: String 
{
  case one   = "value one"
  case two   = "value two"
  case three = "value three"
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)