0

I need to sort my post array, so that it will be arranged by its date. I think a solution is by looping trough the array and reorder it by creating new array that contain the post. So here is my code:

let newPostArray : NSMutableArray = NSMutableArray()

    for post in postArray{

        print("sini3")

        let postDict = post as? NSDictionary

        if postDict!["timeAgo"]?.rangeOfString("d") != nil{

            newPostArray.addObject(post)
            //here is the problem

        }else if postDict!["timeAgo"]?.rangeOfString("w") != nil{

            newPostArray.addObject(post)

        }else if postDict!["timeAgo"]?.rangeOfString("m") != nil{

            newPostArray.addObject(post)

        }else{

            newPostArray.addObject(post)

        }

        print("jeng jeng \(newPostArray)")
    }

My logic is, after newPostArray.addObject(post) the loop continue to the next index and observe the second post and so on. How can I do that? Or is there any way I can reorder the array?

Larme
  • 24,190
  • 6
  • 51
  • 81
Ega Setya Putra
  • 1,645
  • 6
  • 23
  • 51
  • You can use `sortedArrayUsingComparator:` – Larme Nov 10 '15 at 16:53
  • @Larme can it be use on array of dictionary? – Ega Setya Putra Nov 10 '15 at 16:58
  • Yes. You can use a custom comparator for your custom object: http://stackoverflow.com/questions/25769107/sort-nsarray-with-sortedarrayusingcomparator But it would always be better to keep a reference to a `NSDate` an not a `NSString` with "timeAgo". Much simpler, and a `NSSortDescriptor` should be enough. – Larme Nov 10 '15 at 16:59
  • 1
    You can use `break` to end execution of a loop or `continue` to go to the next iteration of the loop. However I would advise you use one of swift's built in sorts. – Tyrelidrel Nov 10 '15 at 17:02
  • Do you have to use NSMutableArray? If you can use a Swift array, you can use the built-in `sort` or `sortInPlace` methods rather than writing your own sorting algorithm. – ConfusedByCode Nov 10 '15 at 20:04

0 Answers0