这是我现在的模型类代码。如何在Swift中按名字排序数组?
final class ContactData
{
static let sharedInstance = ContactData()
private var contactList : [Contact] =
[Contact(name:"Mike Smith",email:"[email protected]"),
Contact(name:"John Doe",email:"[email protected]"),
Contact(name:"Jane Doe",email:"[email protected]")]
private init()
{
// SORTING HERE
}
var index = 0
func newContact(new:Contact)
{
contactList.append(new)
//sort
}
func updateContact(updated:Contact)
{
contactList[index]=updated
//sort
}
func previousContact() -> Contact
{
index-=1
if index < 0
{
index = contactList.count-1
}
return contactList[index]
}
func nextContact() -> Contact
{
index+=1
if index == contactList.count
{
index = 0
}
return contactList[index]
}
func firstContact() -> Contact
{
return contactList[0]
}
func currentContact() -> Contact
{
return contactList[index]
}
}
一切运行正常,但我已经尝试使用字母排序的Contact
在数组:
var sortedContacts = contactList.sorted{
$0.localizedCaseinsensitiveCompare($1)==ComparisonResult.orderedAscending}
}
但我得到一个错误:
Value of type '
Contact
' has no member 'localizedCaseinsensitiveCompare
'
通过提问看这里我只能找到这种单一的方式来按字母顺序排列数组。
我正在斯威夫特3和Xcode的8.3
这个解决方案需要考虑的一些事情。一切只与'name'有关。这假定你总是想按名称比较并忽略电子邮件。它将具有相同名称但不同电子邮件的两个不同联系人对等。这可能会导致很多微妙的错误。这可能是最好的,如果电子邮件比较的名称是平等的。 – rmaddy
我的评论是给OP提供他的自定义排序 –
或比较说明 –