简体   繁体   English

Swift • 枚举可以有多个案例吗?

[英]Swift • Can Enums have to many Cases?

I am working on a Swift App which uses an Enum .我正在开发一个使用Enum的 Swift 应用程序。 However, this Enum will have a bunch of cases.但是,这个 Enum 会有一堆案例。 Maybe 1,000 or even more.也许 1,000 甚至更多。

Code代码

enum Name: Int, CaseIterable {
    case name1
    case name2
    case name3
    // Many more...
    
    var string: String {
        switch self {
            case name1: return "Name 1"
            case name2: return "Name 2"
            case name3: return "Name 3"
            // Many more...
        }
    }
}

Question: Will an Enum with more than 1,000 Cases work?问题:超过 1,000 个案例的 Enum 是否有效? Or will there be a problem?还是会出问题? Which other Data Structure is the best fit in this case?在这种情况下,哪种其他数据结构最适合?

Question 2: the Enum has also computed Properties with Switch-Statements in it.问题 2: Enum 还计算了其中包含 Switch-Statements 的属性。 Is there any Problem with Switch-Statements with over 1,000 Cases?超过 1,000 个案例的 Switch 语句有什么问题吗?

Thanks a lot for your help!非常感谢你的帮助!

You can try something like this -你可以试试这样的——

  1. Store the known list of valid names in a json resource file.将已知的有效名称列表存储在 json 资源文件中。
  2. Add a failable initializer on your data model that validates the name value against this known list of names from that json.在您的数据模型上添加一个可失败的初始值设定项,以根据该 json 中的此已知名称列表验证名称值。 If you provide an invalid name value (that's not known in names json) - init will fail and your data model will not be instantiated.如果您提供无效的名称值(在名称 json 中未知) - init 将失败并且您的数据模型将不会被实例化。
  3. Data model's name property is still a String - not an enum case.数据模型的名称属性仍然是一个String ——而不是一个枚举大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM