Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string case name of a enum whose rawType is Int [duplicate]

Tags:

enums

swift

I want a enumeration of countries, like:

enum Country: Int {
    case Afghanistan
    case Albania
    case Algeria
    case Andorra
    //...
}

There are two main reasons why I choose Int as its rawValue type:

  1. I want to determine the total count of this enumeration, using Int as rawValue type simplifies this:

    enum Country: Int {
        case Afghanistan
        // other cases
        static let count: Int = {
            var max: Int = 0
            while let _ = Country(rawValue: max) { max = max + 1 }
            return max
        }()
    }
    
  2. I also need a complicated data structure that represents a country, and there is an array of that data structure. I can easily subscript-access certain country from this array using Int-valued enumeration.

    struct CountryData {
         var population: Int
         var GDP: Float
    }
    
    var countries: [CountryData]
    
    print(countries[Country.Afghanistan.rawValue].population)
    

Now, I somehow need to convert a certain Country case to String(aka. something like

let a = Country.Afghanistan.description // is "Afghanistan"

Since there are lots of cases, manually writing a conversion-table-like function seems unacceptable.

So, how can I get these features at once ?:

  1. Use enumeration so potential typo-caused bugs can be found during compile time. (Country.Afganistan won't compile, there should be an 'h' after 'g', but some approach like countries["Afganistan"] will compile and may cause runtime errors)
  2. Be able to determine the total country count programmatically (likely to be able to determine at the compile time, but I don't want to use a literal value and keep in mind to change it properly every time I add or remove a country)
  3. Be able to easily subscript-like access a metadata array.
  4. Be able to get a string of a case.

Using enum Country: Int satisfies 1, 2, 3 but not 4

Using enum Country: String satisfies 1, 3, 4 but not 2 (use Dictionary instead of Array)

like image 994
Nandin Borjigin Avatar asked Mar 21 '17 10:03

Nandin Borjigin


1 Answers

To print an enum's case as String, use:

String(describing: Country.Afghanistan)

You can create you data structure something like:

enum Country
{
    case Afghanistan
    case Albania
    case Algeria
    case Andorra
}

struct CountryData
{
    var name : Country
    var population: Int
    var GDP: Float
}

var countries = [CountryData]()
countries.append(CountryData(name: .Afghanistan, population: 2000, GDP: 23.1))
print(countries[0].name)
like image 160
PGDev Avatar answered Oct 11 '22 10:10

PGDev