我的对象看起来像:
object = [[section: "section1", order: "1"],
[section: "section2", order: "1"],
[section: "section1", order: "2"],
[section: "section2", order: "2"]]
我想对它进行排序,结果如下:
[[section: "section1", order: "1"],
[section: "section1", order: "2"],
[section: "section2", order: "1"],
[section: "section2", order: "2"]]
所以我需要按部分排序,并在每个部分按顺序排序。
这就是我正在做的事情:
return Observable.from(realm
.objects(Section.self).sorted(byProperty: "order", ascending: true)
字符串“section ..”仅用于示例,它可以是其他东西所以我不能只使用该字符进行排序。我需要X字符串的真正优先级。
答案 0 :(得分: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)
答案 1 :(得分:0)
let object = [["section": "section1", "order": "2"],
["section": "section2", "order": "2"],
["section": "section1", "order": "1"],
["section": "section2", "order": "1"],
["section": "section5", "order": "3"],
["section": "section6", "order": "1"],
["section": "section5", "order": "1"]]
let Ordered = object.sorted{$0["order"]! < $1["order"]! }
let OrderedObjects = Ordered.sorted{$0["section"]! < $1["section"]! }
print(OrderedObjects)
//[["section": "section1", "order": "1"], ["section": "section1", "order": "2"], ["section": "section2", "order": "1"], ["section": "section2", "order": "2"], ["section": "section5", "order": "1"], ["section": "section5", "order": "3"], ["section": "section6", "order": "1"]]
答案 2 :(得分:0)
使用协议
struct A {
var firstName: String?
var lastName: String?
}
protocol StringSortable {
var property1: String {get}
var property2: String {get}
}
extension A: StringSortable {
var property1: String {
return firstName ?? ""
}
var property2: String {
return lastName ?? ""
}
}
let array1 = [A(firstName: "Dan", lastName: "P2"), A(firstName: "Han", lastName: "P1"), A(firstName: "Dan", lastName: "P0"), A(firstName: "Han", lastName: "P8")]
let sortArray = array1.sorted {
$0.property1 == $1.property1 ? $0.property2 < $1.property2 : $0.property1 < $1.property1
}
print(sortArray)
Dan P0
Dan P2
Han P1
韩P8