如何获取枚举类型为Int的字符串名称

9

我需要一个国家的枚举列表,例如:

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

我选择使用Int作为其rawValue类型的主要原因有两个:

  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)
    
现在,我需要将特定的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(使用字典而不是数组)。

'g'之后的'h'是什么意思? - Archerlly
这个问题不是重复的,因为这个问题中的“rawType is Int”是独特且必要的。那里的答案说要重新声明枚举为String类型。 - pkamb
1个回答

9
为了将枚举类型的case打印成字符串形式,请使用以下代码:
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)

1
这个答案似乎在Swift 5中已经过时了。 - pkamb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接