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

标签 swift swift2

我有以下类(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/

相关文章:

iOS9 应用传输安全 : Allow insecure HTTP loads only on certain subpages

iOS:UISearchBar 显示为有色

swift - NSTabView 背景颜色

arrays - 如何制作一个可以让我制作元素并将它们添加到数组的函数?

设备上使用 xCode 6.4 和 xCode beta 的 iOS 应用程序

iOS UI 测试以调整 SwiftUI 应用程序上的选择器值

ios - SQLite3 在 iOS 应用程序中生成 no such table 错误

ios - 从 URL 将图像保存到库,重命名并使用 Swift 共享

ios - 用图像填充 UICollectionView 返回 nil : Swift 2

ios - 无法将 TableView @IBOutlet 连接到 Swift 2 中的 ViewController