![](/img/trans.png)
[英]Sorting dictionary keys based on a value of the tuple associated with the key in swift
[英]Array Sorting based on dictionary key:value in swift
野兔是一個數組,我想基於數組字典鍵值按升序或降序排序。
//Array Model
[
{
arrival_time:"12:85"
depart_time:"35:55"
price:"55.30"
},
{
arrival_time:"09:15"
depart_time:"18:20"
price:"10.50"
},
{
arrival_time:"15:30"
depart_time:"19:15"
price:"101.50"
}
]
//Here is my swift class and method
class SortClass: NSObject {
@objc func sortBusses (array:[Bus], sortKey:String) -> [Bus] {
//Sort array here...
return array
}
}
注意:我使用的是Xcode 8.0,Objective-C橋接Swift
我是新來的迅速。 請指導我
如果您的Bus
類的類型為NSObject
則可以使用sort函數和valueForKey
檢索sortKey
的值。
@objc func sortBusses (array:[Bus], sortKey:String) -> [Bus] {
let sortValue: (Bus) -> String? = {
$0.value(forKey: sortKey) as? String
}
return array.sorted {
sortValue($0.0)! < sortValue($0.1)!
}
}
我通過使用排序描述符嘗試了您的數組
我的代碼:
let arrayInput:NSArray = [["arrival_time":"12:85","depart_time":"35:55","price":"55.30"],
["arrival_time":"09:15","depart_time":"18:20","price":"10.50"],
["arrival_time":"15:30","depart_time":"19:15","price":"101.50"]];
//descending order
var descriptor: SortDescriptor = SortDescriptor(key: "arrival_time", ascending: false)
var sortedResults: NSArray = arrayInput.sortedArray(using: [descriptor])
print("sortedResults \(sortedResults)");
希望能幫助到你
快樂的編碼...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.