0

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

asked Oct 9, 2016 at 15:40

2 Answers 2

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)!
 }
 }
answered Oct 9, 2016 at 15:53

2 Comments

Just noticed a mistake, the 0ドル refers to a pair of Bus objects that you are supposed to compare. You use 0ドル.0 and 0ドル.1 to access each object.
its giving error (expected type) in second character $ sign :(
0

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

answered Oct 9, 2016 at 16:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.