我需要一个国家的枚举列表,例如:
enum Country: Int {
case Afghanistan
case Albania
case Algeria
case Andorra
//...
}
我选择使用Int
作为其rawValue类型的主要原因有两个:
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 }() }
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)
Country
格式转换为String
格式(类似于)。let a = Country.Afghanistan.description // is "Afghanistan"
由于有很多情况,手动编写类似转换表的函数似乎是不可接受的。那么,如何一次性获得这些功能呢?
1. 使用枚举,以便在编译时找到潜在的因拼写错误引起的错误。(Country.Afganistan将无法编译,应该在"g"后面加上一个"h",但像countries["Afganistan"]这样的方法将编译并可能导致运行时错误) 2. 能够以编程方式确定总国家数量(可能能够在编译时确定,但我不想使用字面值,并时刻记住每次添加或删除国家时要适当更改它) 3. 能够轻松地像下标一样访问元数据数组。 4. 能够获取
case
的字符串。使用
enum Country: Int
满足了1、2、3,但不满足4。使用
enum Country: String
满足了1、3、4,但不满足2(使用字典而不是数组)。