如何获取 rawType 为 Int 的枚举的字符串大小写名称



我想要一个国家的枚举,例如:

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

我选择Int作为其原始值类型有两个主要原因:

  1. 我想确定此枚举的总数,使用Int作为 rawValue 类型可以简化此操作:

    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. 我还需要一个代表一个国家的复杂数据结构,并且有一个数据结构的数组。我可以使用 Int-值枚举轻松地从这个数组中下标访问某个国家/地区。

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

现在,我不知何故需要将某个Country案例转换为String(又名类似的东西)

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

由于有很多情况,手动编写类似转换表的函数似乎是不可接受的。

那么,我怎样才能一次获得这些功能呢?

  1. 使用枚举,以便在编译时发现潜在的拼写错误引起的错误。(Country.Afganistan 不会编译,"g"后面应该有一个"h",但某些方法(如 countries["Afganistan")会编译并可能导致运行时错误)
  2. 能够以编程方式确定国家/地区
  3. 总数(可能能够在编译时确定,但我不想使用文字值,并记住每次添加或删除国家/地区时都要正确更改它)
  4. 能够轻松地像下标一样访问元数据数组。
  5. 能够得到一串case.

使用enum Country: Int满足 1、2、3 而不是 4

使用enum Country: String满足 1、3、4 但不满足 2(使用字典而不是数组)

要将enum's大小写打印为String,请使用:

String(describing: Country.Afghanistan)

您可以创建如下数据结构:

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)

最新更新