如何获得 Swift 枚举的计数? [英] How do I get the count of a Swift enum?
本文介绍了如何获得 Swift 枚举的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何确定 Swift 枚举中的案例数?
How can I determine the number of cases in a Swift enum?
(我想避免手动枚举所有值,或使用旧的enum_count 技巧" 如果可能.)
(I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)
推荐答案
从 Swift 4.2 (Xcode 10) 开始,您可以声明符合 CaseIterable
协议,这适用于所有没有关联值的枚举:
As of Swift 4.2 (Xcode 10) you can declare
conformance to the CaseIterable
protocol, this works for all
enumerations without associated values:
enum Stuff: CaseIterable {
case first
case second
case third
case forth
}
现在简单地获得案例数量
The number of cases is now simply obtained with
print(Stuff.allCases.count) // 4
有关详细信息,请参阅
这篇关于如何获得 Swift 枚举的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文