0

I get a certain response from the server which looks like so...

[
    {
        "theCode": A12345,
        "id": 2980,
        "name": “HELLO”
    },
    {
        "theCode": A12345,
        "id": 2986,
        "name": "HELLO THERE”
    },
    {
        "theCode": A12345,
        "id": 2987,
        "name": "HOW ARE YOU”
    }
]

Once the api is called, I store the above data in an array. It is given like so...

if let myArray = (sdfg["entries"] as? NSMutableArray) {
    print(myArray) 

} 

I would like the name in the above response to be sorted in ascending order based on the id. How can this be achieved...?

emrcftci
  • 3,355
  • 3
  • 21
  • 35
  • 2
    Does this answer your question? [Swift how to sort array of custom objects by property value](https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – dahiya_boy Mar 09 '20 at 11:07

1 Answers1

1
let sortedResults = NSMutableArray(myArray.sortedArray(using: [NSSortDescriptor(key: "id", ascending: true)]))
teja_D
  • 383
  • 3
  • 18
  • I wanted the resulting sorted array as `NSMutableArray`. But when I do this..`let sortedResults = self.arrResult1.sortedArray(using: [NSSortDescriptor(key: "id", ascending: true)]) as! NSMutableArray` then I get a crash saying `Could not cast value of type 'Swift.__SwiftDeferredNSArray’ to 'NSMutableArray'` @teja_D – user13032222 Mar 09 '20 at 11:17
  • @user13032222 Why do you want it as NSMutableArray? – teja_D Mar 09 '20 at 11:20
  • Because I'm passing the array to another view controller as NSMutableArray itself. – user13032222 Mar 09 '20 at 11:21
  • You are using swift now so use swift arrays which are easier to maintain. – teja_D Mar 09 '20 at 11:23
  • Cannot upvote since I have less than 15 reputation @teja_D..:) – user13032222 Mar 09 '20 at 11:31