Sort
- A が大きい場合に true な関数を指定する
swift
let cities = ["世田谷区", "日野市", "目黒区", "八王子市", "檜原村", "瑞穂町"]
let cityPriority = ["区" : 4, "市": 3, "町": 2, "村": 1]
let sortedCities = cities.sorted(by: { (a, b) -> Bool in
if let sA = a.last,
let sB = b.last,
let pA = cityPriority[String(sA)],
let pB = cityPriority[String(sB)] {
return pA > pB
}
return a > b
})
debugPrint(sortedCities)
swift
// そのまま
.sorted(by: { (a, b) in a > b })
// ひらがなカタカナ混在でも対応。先頭数字の並び替えにも対応してる
.sorted(by: { (a, b) in a.localizedStandardCompare(b) == .orderedAscending })
swift
// メンバに適用する場合は sortDescriptor 使う
pathNodes.sorted(using: SortDescriptor(\.name, comparator: .localizedStandard))