Update / change the rawValue of a enum in Swift

后端 未结 2 1844
既然无缘
既然无缘 2021-01-12 08:18

Taking the below enum for instance

enum Name : String {

  case Me = \"Prakash\"
  case You = \"Raman\"

}

Can I do the following

相关标签:
2条回答
  • 2021-01-12 08:33

    Short answer: No, you can't.

    Enumeration types are evaluated at compile time.
    It's not possible to change raw values nor to add cases at runtime.

    The only dynamic behavior is using associated values.

    Reference: Swift Language Guide: Enumerations

    0 讨论(0)
  • 2021-01-12 08:42

    No you cannot. Instead You can redefine your enum to contain associated values instead of raw values.

    enum Name {
        case Me(String)
        case You(String)
        case Last(String)
    }
    
    var me = Name.Me("Prakash")
    print(me)
    me = .You("Raman")
    print(me)
    me = .Last("Singh")
    print(me)
    
    0 讨论(0)
提交回复
热议问题