ios - 斯威夫特:“致命错误:newElements.underestimatedCount 被高估了”——这个错误是什么意思?
问题描述
我有一个 tableView,它的数据源是一个计算数组allItems:
var pendingItems: [Item] = []
var loadingItems: [Item] = []
var processedItems: [Item] = []
var allItems: [Item] {
return processedItems + loadingItems + pendingItems
}
有时,在运行应用程序时,我会收到此错误: Thread 1: Fatal error: newElements.underestimatedCount was an overestimate。
当我尝试通过此函数中的索引到达元素时,似乎会发生这种情况:
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
承诺不会大于序列中元素的数量,并且在序列协议中默认值为零。查看
@inlinable
public var underestimatedCount: Int {
return 0
}
此外,在收集协议中,其默认值与计数相同。查看
@inlinable
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return count
}
因此,由于这种默认实现,直接使用Collection underestimatedCount
肯定不如使用Sequence常见,因为 Collection 保证非破坏性迭代,并且在大多数情况下underestimatedCount
只会返回count
.
当然,自定义集合类型可以提供它们自己的实现underestimatedCount
——给出它们包含多少元素的下限,以一种可能比它们的count
实现更有效的方式,这可能是有用的。
推荐阅读
- flask - Flask WTForms:为什么我上传文件的 POST 请求没有发送文件数据?
- reactjs - react-router - 无法在 this.props.location 中获取信息
- javascript - 为什么 event.preventDefault() 能够阻止子元素的默认浏览器行为?
- c# - 便携库 ObservableCollection 绑定错误
- python - 有没有更好(更有效)的方法从元组中删除项目?
- javascript - 使用 javascript 提取所有 css 选择器
- html - 如何覆盖嵌套 HTML 文档中的 CSS?
- c++ - 卡住 LNK1328:缺少字符串表
- angular - 更新服务值时在组件上运行功能(Angular 6)
- angular - 角度 7.0 pwa 服务人员未加载 css 文件