如何获得Swift枚举的计数? [英] How do I get the count of a Swift enum?
问题描述
如何确定Swift枚举中的个案数量?
How can I determine the number of cases in a Swift enum?
(I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)
推荐答案
我不知道有任何通用的方法来计算枚举数量。但是我注意到,枚举情况的 hashValue
属性是递增的,从零开始,并且按照命名案例的顺序确定。所以,最后一个枚举的哈希加一个对应于个案的数量。
I'm not aware of any generic method to count the number of enum cases. I've noticed however that the hashValue
property of the enum cases is incremental, starting from zero, and with the order determined by the order in which the cases are declared. So, the hash of the last enum plus one corresponds to the number of cases.
例如使用此枚举:
enum Test {
case ONE
case TWO
case THREE
case FOUR
static var count: Int { return Test.FOUR.hashValue + 1}
}
计数
返回4。
我不能说这是一个规则,或者将来会有变化,所以自己使用风险:)
I cannot say if that's a rule or if it will ever change in the future, so use at your own risk :)
这篇关于如何获得Swift枚举的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!