swift - 如何获取 Swift 枚举的计数?

标签 swift enums count

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

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

最佳答案

从 Swift 4.2 (Xcode 10) 开始,您可以声明 符合 CaseIterable 协议(protocol),这适用于所有 没有关联值的枚举:

enum Stuff: CaseIterable {
    case first
    case second
    case third
    case forth
}

现在可以简单地通过以下方式获得案例数

print(Stuff.allCases.count) // 4

有关详细信息,请参阅

关于swift - 如何获取 Swift 枚举的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27094878/

相关文章:

ios - UIScrollView 不在 Swift 中滚动

swift - "Extensions may not contain stored properties"除非你是苹果?我错过了什么?

java - Jackson 枚举序列化和反序列化

Java 无法将枚举用作注释的字符串参数(例如 : Jackson)

sql - 如何仅按特定列值的前几个字母对 SQL 查询进行分组?

swift - 在 macOS 上的 SwiftUI NavigationView 中切换侧边栏

ios - 如何使自定义单元格中的 UILabel 显示保存在 UITableView 中的更改

java - 使用枚举?

mysql - 这个简单的查询有什么问题?

r - x 没有适用于 'tbl_vars' 的方法应用于类 "c(' double', 'numeric' ) 的对象”