数组基于字典键排序:swift中的值

时间:2016-10-09 15:40:36

标签: ios arrays swift sorting

Hare是一个数组,我想根据数组字典键值按升序或降序排序。

//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

我是新手。请指导我

2 个答案:

答案 0 :(得分:2)

You can use the sort function and valueForKey to retrieve the value of your sortKey given your Bus class is of type NSObject.

@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)!
        }
    }

答案 1 :(得分:0)

我使用排序描述符

尝试使用您的数组

我的代码:

    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)");

希望有所帮助

快乐的编码......