如何获取Swift枚举的计数? [英] How do I get the count of a Swift enum?

查看:355
本文介绍了如何获取Swift枚举的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定Swift枚举中的个案数量?



(我想避免手动枚举所有值,或使用旧的 enum_count trick 如果可能的话)。

解决方案

我不知道有任何通用的方法来计算枚举个案的数量。然而,我注意到枚举例子的 hashValue 属性是增量的,从零开始,并且顺序由声明的顺序决定。所以,最后一个枚举的哈希加上一个对应的个案数。



例如使用此枚举:

 枚举测试{
case ONE
case TWO
case THREE
case FOUR

static var count:Int {return Test.FOUR.hashValue + 1}
}

count

我不能说如果这是一个规则,或者如果它会在将来改变,所以自己使用风险:)


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.)

解决方案

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.

For example with this enum:

enum Test {
    case ONE
    case TWO
    case THREE
    case FOUR

    static var count: Int { return Test.FOUR.hashValue + 1}
}

count returns 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆