簡體   English   中英

字典中數組的索引錯誤(Swift 3.0)

[英]Indexing error with an array in a dictionary (Swift 3.0)

我在表視圖中顯示索引對象時遇到問題。 我已根據對象名稱的首字母將這些對象索引為客戶列表。 索引結果像這樣放入字典中

{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
}

通過實現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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM