我有一个这样的对象:
enum State {
case starting
case inProgress
case done
}
struct MyData {
var state: State
}
var array: [MyData]
现在我要排序array
以先starting
项,然后是inProgress
项,然后是done
项。我怎么能这样做?
感谢您的帮助。
答案 0 :(得分:3)
试试这个(游乐场代码)
enum State: Int {
case starting
case inProgress
case done
}
struct MyData {
var state: State
}
let myData1 = MyData(state: .inProgress)
let myData2 = MyData(state: .done)
let myData3 = MyData(state: .starting)
let myData4 = MyData(state: .starting)
let myData5 = MyData(state: .inProgress)
var array = [myData1, myData2, myData3, myData4, myData5]
var sortedArray = array.sorted() { $0.state.rawValue < $1.state.rawValue }
print(sortedArray)
此方法使用枚举的rawValue int对项目进行排序。我从上面的print语句中得到了预期的输出。
答案 1 :(得分:1)
一种可行的方法。
让State
符合Comparable
enum State: Int, Comparable {
case starting = 0
case inProgress = 1
case done = 2
static func <(lhs: State, rhs: State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
使用state
let elms: [MyData] = ...
let sorted = elms.sorted { $0.state < $1.state }