gpt4 book ai didi

Swift - 如何使用对象数组对表进行分组

转载 作者:行者123 更新时间:2023-11-28 08:33:14 25 4
gpt4 key购买 nike

我有以下类(class):

class ProviderSchedule : AnyObject {

var providerUid : String = ""
var lastName : String = ""
var firstName : String = ""
var scheduleRegion : String = ""
var scheduleAmount : Float = 0

init () {

}


}

然后我创建这个对象的数组,以便为​​我的 UITableView 设置源。

var tableData : Array<ProviderSchedule> = []

我的表函数是:

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}

func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1
}

我需要按以下方式对数据进行分组:

lastNamefirstName 这样名字就会出现在表格的组部分。

Any clue how to do that?

最佳答案

将您的数据转换为更适合包含组的表格的格式。创建一个类来表示组 key ,如下所示:

class GroupKey : Hashable {
let firstName : String
let lastName : String
init(fn:String, _ ln:String) {
firstName = fn
lastName = ln
}
... // Implement Hashable and Equatable
}

现在制作一个 GroupKey 对象数组,并按需要对它们进行排序:

var groupSet = Set<GroupKey>()
for s in tableData {
groupSet.insert(GroupKey(s.firstName, s.lastName))
}
let sortedGroups = Array(groupSet)
sortedGroups.sort {
$0.firstName < $1.firstName
|| ($0.firstName == $1.firstName && $0.lastName < $1.lastName)
}

准备时间表组:

var scheduleGroup = [[ProviderSchedule]]()
for g in sortedGroups {
scheduleGroup.append(
tableData.filter{$0.firstName == key.firstName && $0.lastName == key.lastName}
)
}

最后,实现提供部分信息的方法:

func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return sortedGroups.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scheduleGroup[section].count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let key = sortedGroups[section]
return "\(key.lastName), \(key.firstName)"
}

关于Swift - 如何使用对象数组对表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38402352/

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