在使用NSSortDescriptor
之前,已经提出并回答了这个问题。但使用Array.sort()
?
struct Sortable {
let isPriority: Bool
let ordering: Int
}
通过一个属性对Sortables
数组进行排序很简单:
sort { $0.ordering < $1.ordering }
但我希望按isPriority
排序,然后按ordering
排序 - 我无法理解这个简单的陈述。
答案 0 :(得分:42)
是的,有一种使用Array.sort()
<强>代码:强>
var sorted = array.sorted({ (s1, s2) -> Bool in
if s1.isPriority && !s2.isPriority {
return true //this will return true: s1 is priority, s2 is not
}
if !s1.isPriority && s2.isPriority {
return false //this will return false: s2 is priority, s1 is not
}
if s1.isPriority == s2.isPriority {
return s1.ordering < s2.ordering //if both save the same priority, then return depending on the ordering value
}
return false
})
排序数组:
true - 10
true - 10
true - 12
true - 12
true - 19
true - 29
false - 16
false - 17
false - 17
false - 17
false - 18
另一个更短的解决方案:
let sorted = array.sorted { t1, t2 in
if t1.isPriority == t2.isPriority {
return t1.ordering < t2.ordering
}
return t1.isPriority && !t2.isPriority
}
答案 1 :(得分:13)
以下是进行此排序的简单说明:
var sorted = array.sort { $0.isPriority == $1.isPriority ? $0.ordering < $1.ordering : $0.isPriority && !$1.isPriority }
答案 2 :(得分:1)
我在Swift 3中创建了一篇关于如何使用它的博客文章,并保持代码简单易读。
你可以在这里找到它:
http://master-method.com/index.php/2016/11/23/sort-a-sequence-i-e-arrays-of-objects-by-multiple-properties-in-swift-3/
您还可以在此处找到包含以下代码的GitHub存储库:
https://github.com/jallauca/SortByMultipleFieldsSwift.playground
这一切的要点,比方说,如果您有位置列表,您将能够这样做:
struct Location {
var city: String
var county: String
var state: String
}
var locations: [Location] {
return [
Location(city: "Dania Beach", county: "Broward", state: "Florida"),
Location(city: "Fort Lauderdale", county: "Broward", state: "Florida"),
Location(city: "Hallandale Beach", county: "Broward", state: "Florida"),
Location(city: "Delray Beach", county: "Palm Beach", state: "Florida"),
Location(city: "West Palm Beach", county: "Palm Beach", state: "Florida"),
Location(city: "Savannah", county: "Chatham", state: "Georgia"),
Location(city: "Richmond Hill", county: "Bryan", state: "Georgia"),
Location(city: "St. Marys", county: "Camden", state: "Georgia"),
Location(city: "Kingsland", county: "Camden", state: "Georgia"),
]
}
let sortedLocations =
locations
.sorted(by:
ComparisonResult.flip <<< Location.stateCompare,
Location.countyCompare,
Location.cityCompare
)
答案 3 :(得分:0)
符合Comparable
! ?
extension Sortable: Comparable {
static func < (sortable0: Sortable, sortable1: Sortable) -> Bool {
sortable0.isPriority == sortable1.isPriority
? sortable0.ordering < sortable1.ordering
: sortable0.isPriority
}
}
这将允许:
sortableArray.sorted()