我目前在2D数组中按字母顺序排序数据时遇到很大的问题。我将尽力为您提供所有细节。
目前,我正在与CNContactStore取得联系。这一切都很好。我可以从联系人中检索所有想要的数据。
现在,我创建了以下结构:
struct FavoritableContact {
let contact: CNContact
var hasFavorited: Bool
}
这样,我声明并初始化了以下数组:
var favoritableContacts = [FavoritableContact]()
检索到联系人后,只需将其附加到收藏夹中即可。
try store.enumerateContacts(with: request, usingBlock: { (contact, stopPointerIfYouWantToStopEnumerating) in
favoritableContacts.append(FavoritableContact(contact: contact, hasFavorited: false))
})
为了按字母顺序在同一数组中对它们进行排序,我只需执行以下操作:
var sortedContacts = favoritableContacts.sorted { $0.contact.familyName < $1.contact.familyName }
现在,如果可能的话,我想创建以下2D数组,
var 2D = [
[FavoritableContact] //"A"
[FavoritableContact], //"B"
[FavoritableContact], //"C"
[FavoritableContact], //"D"
...
]
我只是不确定如何将我的sortedContacts数组和按字母顺序分开。
我在这里很新,如果我忘记了一些东西,或者我没有做正确的事,请告诉我。
正如评论中所指出的那样,以首字母作为键的字典可能是更好的选择,因为它更容易访问,尽管您可能有理由要使用2d数组。为此,您可以执行以下操作:
//Create an empty array filled with 26 arrays of FavorableContact
var array2d = Array<[FavoritableContact]>(repeating: [FavoritableContact](), count: 26)
//Find the ascii value for "A" to use as your base
let aAscii = Int("A".unicodeScalars.filter({ $0.isASCII }).map({ $0.value })[0]) //This returns 65, btw, so you could also just hardcode
//Go through your original array, find the first letter of each contact, and append to the correct array
favoritableContacts.forEach { (contact) in
//Get the ascii value for the first letter
let firstLetter = Int(contact.contact.familyName.prefix(1).uppercased().unicodeScalars.filter({ $0.isASCII }).map({ $0.value })[0])
//Append to the array for this letter by subtracting the ascii value for "A" from the ascii value for the uppercased version of this letter.
array2d[firstLetter - aAscii].append(contact)
}
这不是世界上最干净的东西,它假定标准的英语字母没有变音符号,符号,数字或其他任何形式。假设这是正确的,那么工作就完成了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句