如何确定Swift枚举中的案例数?
(如果可能的话,我想避免使用manually enumerating through all the values,或者使用旧的"enum_count trick“。)
发布于 2014-11-24 06:03:26
我有更详细的a blog post,但是只要你的枚举的原始类型是一个整数,你就可以这样添加一个计数:
enum Reindeer: Int {
case Dasher, Dancer, Prancer, Vixen, Comet, Cupid, Donner, Blitzen
case Rudolph
static let count: Int = {
var max: Int = 0
while let _ = Reindeer(rawValue: max) { max += 1 }
return max
}()
}
发布于 2015-10-20 23:51:01
我定义了一个可重用的协议,它根据Nate Cook发布的方法自动执行案例计数。
protocol CaseCountable {
static var caseCount: Int { get }
}
extension CaseCountable where Self: RawRepresentable, Self.RawValue == Int {
internal static var caseCount: Int {
var count = 0
while let _ = Self(rawValue: count) {
count += 1
}
return count
}
}
然后我可以像下面这样重用这个协议:
enum Planet : Int, CaseCountable {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
//..
print(Planet.caseCount)
发布于 2016-03-24 03:53:19
创建静态allValues数组,如此answer所示
enum ProductCategory : String {
case Washers = "washers", Dryers = "dryers", Toasters = "toasters"
static let allValues = [Washers, Dryers, Toasters]
}
...
let count = ProductCategory.allValues.count
当您要枚举值时,这也很有用,并且适用于所有枚举类型
https://stackoverflow.com/questions/27094878
复制相似问题