我有一个tableView,它有数据源作为计算数组allItems:
var pendingItems: [Item] = []
var loadingItems: [Item] = []
var processedItems: [Item] = []
var allItems: [Item] {
return processedItems + loadingItems + pendingItems
}
有时,在运行应用程序时,我收到此错误:线程1:致命错误:newElements.underestimatedCount是一个高估。
看起来当我尝试通过此函数中的索引到达元素时会发生这种情况:
func getCellContent(at index: Int) -> (url: String, status: String) {
return (url: queue.allItems[index].url, status: queue.allItems[index].status.description)
}
这是一个截图:https://www.dropbox.com/s/b9miuyiz1em56mk/Screen%20Shot%202019-04-12%20at%202.06.25%20PM.png?dl=1
有人可以解释为什么会这样吗?我真的很感激任何帮助!
数据源方法(来自视图控制器):
extension WebSearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return presenter.getNumberOfRows()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WebPageTableViewCell", for: indexPath) as! WebPageTableViewCell
let (url, status) = presenter.getCellContent(at: indexPath.row)
cell.addressLabel.text = url
cell.statusLabel.text = status
return cell
}
}
从演示者那里获取方法:
func getNumberOfRows() -> Int {
return queue.allItems.count
}
func getCellContent(at index: Int) -> (url: String, status: String) {
return (url: queue.allItems[index].url, status: queue.allItems[index].status.description)
}
这是我的Item
:
class WebPage: NSObject {
var url: String
var status: URLStatus
init(url: String, status: URLStatus = .unchecked) {
self.url = url
self.status = status
}
func changeStatus(to newStatus: URLStatus) {
self.status = newStatus
}
static func == (lhs: WebPage, rhs: WebPage) -> Bool {
return lhs.url == rhs.url
}
}
你的代码绝对正常,很难说是错误的根本原因。以下是关于underestimatedCount
的一些关键功能,希望它有助于知识目的。
underestimatedCount
承诺收集的计数不会大于序列中的元素数量,并且在序列协议中默认值为零。 Check
@inlinable
public var underestimatedCount: Int {
return 0
}
此外,在收集协议中,其默认值与count相同。 Check
@inlinable
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return count
}
因此,由于这个默认实现,直接使用Collection的underestimatedCount
绝对不如使用Sequence更常见,因为Collection保证非破坏性迭代,并且在大多数情况下underestimatedCount
将返回count
。
当然,虽然自定义集合类型可以提供它们自己的underestimatedCount
实现 - 给出它们包含的元素数量的下限,可能比它们的count
实现更有效,这可能是有用的。