I have Contact model and I want to sort by [firstLetter, fullName] into [section,row] for UITableView in this way "FAVORITES" at startIndex, "#" at endIndex and between them are sorted letters.
For example: ["A", "C", "E", "#", "FAVORITES"] into ["FAVORITES", "A", "C", "E", "#"]
This is model
class Contact: Object {
dynamic var fullName = ""
dynamic var firstLetter = ""
}
Here's UITableViewController, where I sort data
class ContactsController: UITableViewController {
// some code
var contacts = try! Realm().objects(Contact.self).filter("isDeleted == false").sorted(by: ["firstLetter","fullName"])
var sections: [String] {
return Set(contacts.value(forKeyPath: "firstLetter") as![String]).sorted()
}
override func viewDidLoad() {
super.viewDidLoad()
setUI()
}
// another code
}
Edit #1
Sorry, I forgot to say that "#" contains contacts where fullName begins with special characters
Answer for my question
var sections: [String] {
return Set(contacts.value(forKeyPath: "firstLetter") as![String]).sorted {
//Favourites sorts before all else
if $0 == "FAVORITES" { return true }
if $1 == "FAVORITES" { return false }
// Symbols sort after all else
if $0 == "#" { return false }
if $1 == "#" { return true }
return $0 < $1
}
}
isFavoriteproperty toContact, then there's no need for two separate arrays, since you can just filter them likecontacts.filter{ $0.isFavorite }orcontacts.filter{ !$0.isFavorite }.Contactstore the first letter if it's already in thefullName?