按两个属性排序

Mak*_*lle 6 ios swift swift3

我的对象看起来像:

object = [[section: "section1", order: "1"],
          [section: "section2", order: "1"],
          [section: "section1", order: "2"],
          [section: "section2", order: "2"]]
Run Code Online (Sandbox Code Playgroud)

我想对它进行排序,得到如下结果:

[[section: "section1", order: "1"],
 [section: "section1", order: "2"],
 [section: "section2", order: "1"],
 [section: "section2", order: "2"]]
Run Code Online (Sandbox Code Playgroud)

所以我需要按部分排序,并在每个部分按顺序排序.

这就是我正在做的事情:

  return Observable.from(realm
            .objects(Section.self).sorted(byProperty: "order", ascending: true)
Run Code Online (Sandbox Code Playgroud)

字符串"section .."仅用于示例,它可以是其他的东西,所以我不能只使用字符进行排序.我需要X字符串的真正优先级.

Las*_*ove 5

要通过两个因素对其进行排序,您可以使用"已排序"方法执行自定义逻辑:以下是您可以在操场中进行测试的示例.

    struct MyStruct {
    let section: String
    let order: String
}
let array = [MyStruct(section: "section1", order: "1"),
             MyStruct(section: "section2", order: "1"),
             MyStruct(section: "section1", order: "2"),
             MyStruct(section: "section2", order: "2")]

let sortedArray = array.sorted { (struct1, struct2) -> Bool in
    if (struct1.section != struct2.section) { // if it's not the same section sort by section
        return struct1.section < struct2.section
    } else { // if it the same section sort by order.
        return struct1.order < struct2.order
    }
}
print(sortedArray)
Run Code Online (Sandbox Code Playgroud)