Swift:按两个以上的可能值排序数组

时间:2018-02-05 10:58:03

标签: swift sorting

我有一个这样的对象:

enum State {
    case starting
    case inProgress
    case done
}

struct MyData {
    var state: State
}

var array: [MyData]

现在我要排序array以先starting项,然后是inProgress项,然后是done项。我怎么能这样做?

感谢您的帮助。

2 个答案:

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