2017-02-10 12 views
0

我在顯示錶視圖中的索引對象時遇到問題。我已根據名稱的第一個字母將對象索引爲客戶列表。索引結果被放入一個字典是這樣字典中的數組索引錯誤(Swift 3.0)

{Char: [Client]} 

字符是客戶的名字和[客戶]爲客戶對象,誰都有自己的名字相匹配的字符的第一個字母組成的數組的第一個字符。當打印出來,這表明了這樣的:

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

然而,當我走在的tableView設置這些頭銜(_的tableView:UITableView的,cellForRowAt indexPath:IndexPath)函數,我得到一個索引出界失誤。客戶端陣列具有計數3和接觸詞典有兩個計數,但所有3個對象它是這樣:我該如何去翻翻字典,適當地個人客戶進入每個單元格

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

有適當的部分標題?我正在使用Swift 3.0。下面我發佈了我如何索引它以及我試圖覆蓋的函數。在cellForRowAt從這個

return letters.count 

更改代碼:

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 
} 
+0

您想爲字母表中的每個字母添加一個部分,然後爲該部分中的每個聯繫人添加一個單元格? – Pierce

+2

設置段數和行數時,代碼的外觀如何? – jherg

+1

你似乎沒有使用部分。你需要每個字母都有一個部分,並使用它在'cellForRow'中找到正確的聯繫人 – Paulw11

回答

0

創建每個字母一個部分,通過實施numberOfSections方法返回此

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

對此:

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