Lokesh Chowdary Lokesh Chowdary - 1 month ago 14
iOS Question

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

I'm new to swift. please guide me

Answer

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