I am fetching data from model i.e Contacts. Then I sort this model as per nameproperty. But the result is not come in sorted manner. I am using following code to sort data:
func filterArrayAlphabatically(contacts : [Contact])
{
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.map({ String($0)})
let all_Contacts = contacts.sorted { $0.name < $1.name } //Sort model data as per name
var result = [String:[Contact]]()
for letter in alphabet
{
result[letter] = []
for cntct in all_Contacts
{
let ctc : Contact! = cntct
let name : String! = ctc.name.capitalized
if name.hasPrefix(letter)
{
result[letter]?.append(cntct)
}
}
}
print("result......\(result)")
}
It gives me output like:
result......["M": [], "K": [<App.Contact: 0x7c6703e0>], "E": [], "U": [], "Y": [], "H": [<App.Contact: 0x7c6701a0>], "X": [], "A": [<App.Contact: 0x7c670120>, <App.Contact: 0x7c670440>], "D": [<App.Contact: 0x7c6700b0>, <App.Contact: 0x7c670160>], "I": [], "R": [], "G": [], "P": [], "O": [], "L": [], "W": [], "C": [], "V": [], "J": [<App.Contact: 0x7c66f990>], "Q": [], "T": [], "B": [], "N": [], "Z": [], "S": [], "F": []]
I want output in sorted manner like:
result......["A": [], "B": [<App.Contact: 0x7c6703e0>], "C": [], "D": []]
What I am doing wrong? Or Is there any other to sort it. Thanks!
EDIT: I tried following code to make correct order:
let sortedArray = result.sorted
{
(struc1, struc2) -> Bool in
return struc1.key < struc2.key
}
Ok, this gives me result in correct order as I want. But the problem is I want to use it, But How I don't know. As I have var arr_Contacts = [String:[Contact]]() . I want to assign sortedArray to arr_Contacts. How Can I do that?
When I assign it gives warning that is:
It gives error:

