Update / change the rawValue of a enum in Swift

﹥>﹥吖頭↗ 提交于 2020-05-08 09:29:08

问题


Taking the below enum for instance

enum Name : String {

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

}

Can I do the following

Change the raw value of one "case" to something else.

Name.Me = "Prak"

Add a new case to the ENUM

Name.Last = "Benjamin"

Thanks!


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/35574928/update-change-the-rawvalue-of-a-enum-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!