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

后端 未结 8 958
[愿得一人]
[愿得一人] 2020-12-14 05:17

If I have an enum with the cases a,b,c,d is it possible for me to cast the string \"a\" as the enum?

8条回答
  •  既然无缘
    2020-12-14 05:40

    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 = "one"
      case two = "two"
      case three = "three"
    }
    
    let anEnum = StringEnum(rawValue: "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"
    }
    

提交回复
热议问题