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

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

问题描述

如何确定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屋!

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