[英]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
看起來 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: $0)! < allCases.firstIndex(of: $1)! }
arrayOfEducationOptions.forEach { print($0) }
請注意,該代碼是一個幼稚的實現,並且隨着案例數量的增加,擴展性會很差。 (它至少具有O(n²)
時間性能,甚至可能更差( O(n²•log n)
)。對於較大的枚舉,您需要重寫它以創建一個結構數組,其中包含來自示例數組的索引枚舉,然后排序。
向枚舉添加可比較的協議?
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: { $0 < $1 })
可能有更好的方法來設置數組中的順序值,同時也具有字符串原始值,但不是我的頭頂
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.