Home > Software design >  Swift sort an array of enums by their enum declared order
Swift sort an array of enums by their enum declared order

Time:05-19

How can I sort my array of enums to be sorted by the 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]

I want to sort arrayOfEducationOptions to get [.gcse, .aLevel, .masters] as per the order declared in the enum

CodePudding user response:

Make it conform to CaseIterable protocol and use the static allCases property:

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

CodePudding user response:

Add a comparable protocol to the enum?

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
   }
}

then you can just sort the array.

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

there may be a better way to set the order values in the array while having the String raw value as well, but not of the top of my head

  • Related