The reason it works for dates in the same month is that it comes after the day in the string. I would recommend to change the date property type from String to Date. If you can not change the property type you would need to create a custom DateFormatter to parse your date strings and sort the resulting dates:
extension Formatter {
static let date: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = .init(identifier: "en_US_POSIX")
formatter.dateFormat = "dd-MM-yyyy-HH:mm"
return formatter
}()
}
extension String {
var customDate: Date? { Formatter.date.date(from: self) }
}
This assumes your date string is always a valid date:
conversations.sort(by: { $0.latestMessage.date.customDate! > $1.latestMessage.date.customDate!})
print(conversations)
This will print:
[Conversation(latestMessage: Message(date: "01-11-2020-00:31")),
Conversation(latestMessage: Message(date: "01-11-2020-00:19")),
Conversation(latestMessage: Message(date: "30-10-2020-20:43")),
Conversation(latestMessage: Message(date: "29-10-2020-20:58"))]
If you can not guarantee your string is always a valid date you can use the nil coalescing operator to provide a default value:
conversations.sort(by: { $0.latestMessage.date.customDate ?? .distantFuture > $1.latestMessage.date.customDate ?? .distantFuture })
print(conversations)