首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何获取Swift枚举的计数?

如何获取Swift枚举的计数?
EN

Stack Overflow用户
提问于 2014-11-24 05:59:31
回答 14查看 70.7K关注 0票数 205

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

(如果可能的话,我想避免使用manually enumerating through all the values,或者使用旧的"enum_count trick“。)

EN

回答 14

Stack Overflow用户

发布于 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
    }()
}
票数 147
EN

Stack Overflow用户

发布于 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)
票数 72
EN

Stack Overflow用户

发布于 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

当您要枚举值时,这也很有用,并且适用于所有枚举类型

票数 36
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27094878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档