How to get the string name of an enum name whose rawType is Int
I want to list countries, for example:
enum Country: Int {
case Afghanistan
case Albania
case Algeria
case Andorra
//...
}
There are two main reasons why I choose Int
rawValue as my type:
-
I want to determine the total score of this enum using
Int
as the 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 }() }
-
I also need a complex data structure representing the country and there is an array of that data structure. I can easily index access to a specific country from this array using an indexed 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 specific case Country
to String
(for example something like
let a = Country.Afghanistan.description // is "Afghanistan"
Since there are many cases, manually writing a function like conversion seems unacceptable.
So how can I get these functions right away ?:
- Use an enumeration so you can catch potential errors caused by common errors at compile time. (Country.Agganistan will not compile, there should be "h" after "g", but some approach like countries ["Afghanistan"] will compile and may lead to runtime errors).
- Be able to determine the total count of a country programmatically (probably be able to determine at compile time, but I don't want to use a literal value and remember to change it correctly every time I add or remove a country)
- Be able to easily file access to an array of metadata.
- Be able to get a string
case
.
Usage enum Country: Int
satisfies 1, 2, 3, but not 4
Usage enum Country: String
satisfies 1, 3, 4, but not 2 (use a dictionary instead of an array)
source to share
To print the case enum's
as String
, use:
String(describing: Country.Afghanistan)
You can create a data structure 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)
source to share