2

I have a list of conversation which needs to be sorted on last updated time. I am able to do this but now i also need to add a check that if user is not included in conversation then it should appear at the end of list.

func sortConversationList () {
self.conversationList = self.conversationList.sorted(by: { $0.lastupdatedTime! > $1.lastupdatedTime! })
    for (index, conversation) in self.conversationList.enumerated() {
        if (conversation.isIncluded == kNo) {
            self.conversationList.move(at: index, to: self.conversationList.endIndex-1)
        }
    }
    self.tableView.reloadData()
}
 mutating func move(at oldIndex: Int, to newIndex: Int) {
        self.insert(self.remove(at: oldIndex), at: newIndex)
    }

but this is not working properly. Any better way to do this in swift ?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
aqsa arshad
  • 801
  • 8
  • 27

1 Answers1

2

Your approach is far too complicated. You have two sorting criteria:

  1. isIncludedtrue values should be sorted before false values,
  2. lastupdatedTime – larger values should be sorted first.

That can be done with a single sort() call:

conversationList.sort(by: { 
    if $0.isIncluded != $1.isIncluded {
        return $0.isIncluded
    } else {
        return $0.lastupdatedTime > $1.lastupdatedTime
    }
})

This assumes isIncluded is a boolean variable (which would be sensible). If it is an integer (as you indicated in the comments) then it is even simpler: (compare Swift - Sort array of objects with multiple criteria):

conversationList.sort(by: {
    ($0.isIncluded, $0.lastupdatedTime) > ($1.isIncluded, $1.lastupdatedTime)
})
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382