[英]Array Sorting based on dictionary key:value in swift
Hare is an array, i want to sort in ascending or descending order based on array dictionary key value. 野兔是一个数组,我想基于数组字典键值按升序或降序排序。
//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
}
}
Note: I'm using Xcode 8.0, Objective-C bridging Swift 注意:我使用的是Xcode 8.0,Objective-C桥接Swift
I'm new to swift. 我是新来的迅速。 please guide me
请指导我
You can use the sort function and valueForKey
to retrieve the value of your sortKey
given your Bus
class is of type NSObject
. 如果您的
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)!
}
}
I tried with your array by using sort descriptor 我通过使用排序描述符尝试了您的数组
My Code : 我的代码:
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)");
Hope it helps 希望能帮助到你
Happy coding ... 快乐的编码...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.