【问题标题】:how to use an array as a case of an enum如何将数组用作枚举的情况
【发布时间】:2025-12-14 11:35:01
【问题描述】:

我正在使用 Swift 5.3 和 Xcode 12.4,并且我有一个包含类型的枚举,其中一种情况基本上是其他情况的数组。 它看起来像这样:

enum Types {
static let type1                             = "type1"
static let type2                             = "type2"
static let type3                             = "type3"
static let type4                             = "type4"
static let type5                             = "type5" 

static let typeArray                         = [type1, type2, type3]

}

我需要将其更改为以下内容,但 Xcode 说“枚举大小写的原始值必须是文字”

enum Types: String, Codable, CaseIterable {
    case type1
    case type2
    case type3
    case type4
    case type5
    case typesArray                         = [type1, type2, type3]
}

任何想法如何将顶部的枚举更改为底部的枚举?谢谢!

【问题讨论】:

  • 为什么需要这个数组案例?为什么不简单地Types.allCases?只需删除您的 typesArray 案例即可。
  • 感谢您的回答 Leo,我编辑了我的问题,希望能更好地解释它。该数组将包含一些案例,而不是全部。
  • 这个Type 不是Types。是Type

标签: ios arrays swift xcode enums


【解决方案1】:

只需创建一个静态属性:


enum Types: String, Codable, CaseIterable {
    case type1, type2, type3, type4, type5
    static let someCases: [Types] = [.type1, .type2, .type3] 
}

Types.someCases  // [type1, type2, type3]

【讨论】:

  • 我现在试一试,然后回复您,谢谢!
  • 如果您需要迭代您的案例,请查看post
  • 我对您的回答投了“赞成票”,我不知道如何将其标记为正确。如果有办法,你能告诉我怎么做吗?
  • 哦,不知道那是那个复选标记的目的。我检查它是正确的答案,非常感谢您的帮助