Swift 按枚举声明的顺序对枚举数组进行排序

Swift sort an array of enums by their enum declared order

如何按照声明的顺序对枚举数组进行排序?

enum EducationOptions: String {
    case gcse = "GCSE"
    case aLevel = "A Level"
    case bachelors = "Bachelors"
    case masters = "Masters"
    case doctorate = "Doctorate"
    case other = "Other"
}

var arrayOfEducationOptions: [EducationOptions] = [.masters, .gcse, .aLevel]

我想按照枚举中声明的顺序对 arrayOfEducationOptions 进行排序以获得 [.gcse, .aLevel, .masters]

使其符合CaseIterable协议并使用静态allCases 属性:

enum EducationOptions: String, CaseIterable {
    case gcse = "GCSE"
    case aLevel = "A Level"
    case bachelors = "Bachelors"
    case masters = "Masters"
    case doctorate = "Doctorate"
    case other = "Other"
}

let arrayOfEducationOptions = EducationOptions.allCases

向枚举添加可比较的协议?

enum EducationOptions: String {
   case gcse = "GCSE"
   case aLevel = "A Level"
   case bachelors = "Bachelors"
   case masters = "Masters"
   case doctorate = "Doctorate"
   case other = "Other"

   var order: Int {
      switch self {
      case .gcse: return 1
      case .aLevel: return 2
      case .bachelors: return 3
      case .masters: return 4
      case .doctorate: return 5
      case .other: return 6
   }
}

extention EquctionOptions: Comparable { 


   static func < (lhs: EducationOptions, rhs: EducationOptions) -> Bool {
      lhs.order < rhs.order
   }
}

然后你就可以对数组进行排序了。

let array = [.masters, .gcse, .aLevel]
let sorted = array.sorted(by: { [=11=] <  })

可能有更好的方法来设置数组中的顺序值,同时也具有 String 原始值,但不是我的想法

Vadim 的想法似乎是正确的,但如果您想对任意 EducationOptions 列表进行排序,您可以使用如下代码:

enum EducationOptions: String, CaseIterable {
    case gcse = "GCSE"
    case aLevel = "A Level"
    case bachelors = "Bachelors"
    case masters = "Masters"
    case doctorate = "Doctorate"
    case other = "Other"
}

let allCases = EducationOptions.allCases

var arrayOfEducationOptions: [EducationOptions] = [.masters, .gcse, .aLevel]
    .sorted {allCases.firstIndex(of: [=10=])! <  allCases.firstIndex(of: )! }

arrayOfEducationOptions.forEach { print([=10=]) }

请注意,该代码是一个简单的实现,随着案例数量的增加,扩展性会很差。 (它至少有 O(n²) 的时间性能,甚至可能更差 (O(n²•log n))。对于更大的枚举,你想重写它以创建一个结构数组,其中包含示例数组中的索引枚举,然后排序 that.