我有一个对话列表,需要在上次更新时间排序。我能够做到这一点,但现在我还需要添加一个检查,如果用户未包含在对话中,那么它应该出现在列表的末尾。
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)
}
但这不能正常工作。有什么更好的方法在swift中做到这一点?
答案 0 :(得分:2)
你的方法太复杂了。您有两个排序标准:
isIncluded
- true
值应在false
值之前排序,lastupdatedTime
- 应首先对较大的值进行排序。可以通过一次sort()
电话完成:
conversationList.sort(by: {
if $0.isIncluded != $1.isIncluded {
return $0.isIncluded
} else {
return $0.lastupdatedTime > $1.lastupdatedTime
}
})
这假设isIncluded
是一个布尔变量(这是明智的)。如果是整数(如评论中所示)
然后它更简单:(比较Swift - Sort array of objects with multiple criteria):
conversationList.sort(by: {
($0.isIncluded, $0.lastupdatedTime) > ($1.isIncluded, $1.lastupdatedTime)
})