【问题标题】:Indexing error with an array in a dictionary (Swift 3.0)字典中的数组索引错误(Swift 3.0)
【发布时间】:2017-02-10 22:35:20
【问题描述】:

我在表格视图中显示索引对象时遇到问题。我已根据客户名称的第一个字母将对象索引为客户列表。索引结果被放入这样的字典中

{Char: [Client]}

Char 是客户端名称的第一个字符,[Client] 是一组客户端对象,它们的名称的第一个字母与 Char 匹配。打印出来的时候是这样的:

{'D': [Client("David"), Client("Dan")]}

但是,当我在 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 函数中设置这些标题时,我得到一个索引越界错误。客户端数组的计数为 3,联系人字典的计数为 2,但所有 3 个对象都是这样:

{'S': [Client("Sam")], 'D': [Client("David"), Client("Dan")]}

如何正确浏览字典以将单个客户带入具有正确部分标题的每个表格单元格?我正在使用 Swift 3.0。下面我发布了我如何索引它以及我试图覆盖的功能。

ClientTableViewController.swift

var clients = Client.loadAllClients()

var contacts = [Character: [Client]]()

var letters: [Character] = []

override func viewDidLoad() {
    super.viewDidLoad()

    letters = clients.map { (name) -> Character in
        return name.lName[name.lName.startIndex]
    }

    letters = letters.reduce([], { (list, name) -> [Character] in
        if !list.contains(name) {
            return list + [name]
        }
        return list
    })

    for c in clients {
        if contacts[c.lName[c.lName.startIndex]] == nil {
            contacts[c.lName[c.lName.startIndex]] = [Client]()
        }

        contacts[c.lName[c.lName.startIndex]]!.append(c)
    }

    for (letter, list) in contacts {
        contacts[letter] = list.sorted(by: { (client1, client2) -> Bool in
            client1.lName < client2.lName
        })
    }
}

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Name", for: indexPath) as! ClientTableViewCell

    cell.clientName?.text = contacts[letters[indexPath.row]]?[indexPath.row].lName

    return cell
}

【问题讨论】:

  • 您想为字母表中的每个字母设置一个部分,然后为该部分中的每个联系人设置一个单元格?
  • 设置节数和行数后你的代码是什么样子的?
  • 您似乎根本没有使用部分。您需要每封信有一个部分,并使用它在cellForRow中找到合适的联系人

标签: ios swift uitableview dictionary


【解决方案1】:

为每个字母创建一个部分,通过实现 numberOfSections 方法返回:

    return letters.count

从这里更改 cellForRowAt 中的代码:

  cell.clientName?.text = contacts[letters[indexPath.row]]?[indexPath.row].lName

到这里:

   cell.clientName?.text = contacts[letters[indexPath.section]]?[indexPath.row].lName

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多