我決定使用字典來使用 API 呼叫填充多個 tableView,而不是使用陣列和異步等待來減少加載時間。我在后臺執行緒中異步呼叫我的所有 API,給每個字典一個從 0 開始遞增的索引,當所有 API 呼叫完成后,我對字典進行排序:
let sortedDictionary = dictionary.sorted {
return $0.key < $1.key
}
然后我填充我的 tableViews;比按順序運行 API 呼叫要快得多。現在我必須以某種方式在洗掉一行時重新排序 tableViews,就像你對標準陣列一樣(我有一個帶有幾個 tableViews 的滾動視圖,另一個 tableView 有一個為每個 tableView 的行;第二個 tableView 是我洗掉行的那個)。這是我的嘗試,但我的邏輯中有一些東西是錯誤的,或者我錯過了一些東西:
func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
//delete object from dictionary
self.dictionary.removeValue(forKey: indexPath.row)
for i in indexPath.row...dictionary.count-1{
if i == dictionary.count-1{
//remove last index in the dictionary at end of loop
self.dictionary.removeValue(forKey: i)
} else{
//increment all dictionary indices past the deleted row down one
let j = i i
let value = dictionary[j]
guard let value = value else {return}
self.dictionary.removeValue(forKey: j)
self.dictionary.updateValue(value, forKey: i)
}
}
}
}
看來我在這里遇到了一個空值:
guard let value = value else {return}
Is this not the correct way to store a dictionary value?
let value = dictionary[j]
Any help is appreciated. Thanks!
uj5u.com熱心網友回復:
我解決了這個問題并將其格式化為模板函式,以便可以在多個字典模型上使用。正如上面提到的,字典可以簡單地排序,但這是另一種方法:
func deleteRows<T>(indexPath: IndexPath, dictionary: inout Dictionary<Int, T>){
if indexPath.row == dictionary.count-1{
//if its the last object in the tableView, delete and return
dictionary.removeValue(forKey: indexPath.row)
return
}
//store last object in dictionary
let lastIndex = dictionary[dictionary.count-1]
for i in indexPath.row...dictionary.count-1{
if i == dictionary.count-2{
//remove last object in the dictionary at end of loop
dictionary.removeValue(forKey: dictionary.count-1)
//append last object
guard let lastIndex = lastIndex else {return}
dictionary.updateValue(lastIndex, forKey: dictionary.count-1)
} else if i < dictionary.count-1{
//increment all dictionary indices past the deleted row down one
let value = dictionary[i i]
guard let value = value else {return}
dictionary.updateValue(value, forKey: i)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454584.html
標籤:swift dictionary uitableview tableview delete-row
