Accessing a String Enum by index

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

I have an enum in C and the index needs to be represented by a String.

How can a Swift enum of String type be used by integer index?

I would like to copy the enum to Swift, set the type to string and define all of the raw values to display text, and then use the C enum value to extract the raw value text for the Swift String enum.

Otherwise I will just create an array of strings.. But the enum would be more usable.

回答1:

In Swift, enum types do not hold its index info of cases (at least, not provided for programmers).

So:

How can a Swift enum of String type be used by integer index?

The answer is "You cannot".


You can bind Int (or enum cases) and String values in many ways other than just create an array of strings..

For example, if your bound Strings can be the same as case labels, you can write something like this:

enum MyEnum: Int {     case foo     case bar     case baz      var string: String {         return String(self)     } }  if let value = MyEnum(rawValue: 0) {     print(value.string) //->foo } 

If your Strings need to be a little more complex to display text, you can use Swift Dictionary to bind enum cases and Strings.

enum AnotherEnum: Int {     case foo     case bar     case baz      static let mapper: [AnotherEnum: String] = [         .foo: "FooString",         .bar: "BarString",         .baz: "BazString"     ]     var string: String {         return AnotherEnum.mapper[self]!     } }  if let value = AnotherEnum(rawValue: 1) {     print(value.string) //->BarString } 

A little bit more readable than a simple array of strings.



回答2:

Simple workaround which is also useful if you want to enumerate a string enum.

enum MyEnum: String {     case foo = "fooString"     case bar = "barString"     case baz = "bazString"      static let allValues = [foo, bar, baz] //must maintain second copy of values }  //enumeration advantage for value in MyEnum.allValues {     print(value) }  //get value by index let value = MyEnum.allValues[1]   print(value) //barString 


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