gpt4 book ai didi

swift - 如何在 Swift 中按名字按字母顺序排列数组?

转载 作者:行者123 更新时间:2023-11-28 06:11:05 29 4
gpt4 key购买 nike

这是我当前的模型类代码。

final class ContactData
{
static let sharedInstance = ContactData()

private var contactList : [Contact] =
[Contact(name:"Mike Smith",email:"mike@smith.com"),
Contact(name:"John Doe",email:"john@doe.com"),
Contact(name:"Jane Doe",email:"jane@doe.com")]


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'

浏览这里的问题,我只能找到按字母顺序排列数组的唯一方法。

我正在运行 Swift 3 和 Xcode 8.3

最佳答案

你应该让你的类 Contact 符合 Comparable 协议(protocol):

class Contact: Comparable, CustomStringConvertible {
let name: String
let email: String
init(name: String, email: String) {
self.name = name
self.email = email
}
var description: String {
return name + " - " + email
}
// provide your custom comparison
static func <(lhs: Contact, rhs: Contact) -> Bool {
return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .orderedAscending ||
lhs.email.localizedCaseInsensitiveCompare(rhs.email) == .orderedAscending
}
// you will need also to make it conform to Equatable
static func ==(lhs: Contact, rhs: Contact) -> Bool {
return lhs.name == rhs.name && lhs.email == rhs.email
}
}

Playground 测试

let c1 = Contact(name:"Mike Smith",email:"mike@smith.com")
let c2 = Contact(name:"John Doe",email:"john1@doe.com")
let c3 = Contact(name:"John Doe",email:"john2@doe.com")
let c4 = Contact(name:"Jane Doe",email:"jane2@doe.com")
let c5 = Contact(name:"Jane Doe",email:"jane1@doe.com")

let people = [c1, c2, c3, c4, c5]
print(people) // "[Mike Smith - mike@smith.com, John Doe - john1@doe.com, John Doe - john2@doe.com, Jane Doe - jane2@doe.com, Jane Doe - jane1@doe.com]\n"
print(people.sorted()) // "[Jane Doe - jane1@doe.com, Jane Doe - jane2@doe.com, John Doe - john1@doe.com, John Doe - john2@doe.com, Mike Smith - mike@smith.com]\n"

关于swift - 如何在 Swift 中按名字按字母顺序排列数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46575227/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com