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