如何使用 'map' 将领域集合更改通知映射到 UITableview 部分?

How to use 'map' to map realm collection change notifications to UITableview sections?

Realm Collection Notifications 在使用 'map' 映射 UITableView 行时工作正常。我如何通过将其映射到 UITableView 部分来实现相同的目的。

对于行,我遵循以下代码:

notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
  guard let tableView = self?.tableView else { return }
  switch changes {
  case .Initial:
    tableView.reloadData()
    break
  case .Update(_, let deletions, let insertions, let modifications):
    tableView.beginUpdates()
    tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: [=11=], inSection: 0) },
      withRowAnimation: .Automatic)
    tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: [=11=], inSection: 0) },
      withRowAnimation: .Automatic)
    tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: [=11=], inSection: 0) },
      withRowAnimation: .Automatic)
    tableView.endUpdates()
    break
  case .Error(let error):
    // An error occurred while opening the Realm file on the background worker thread
    fatalError("\(error)")
    break
  }
}

对于部分,我使用:

tableview.beginUpdates()
                    for insertIndex in insertions {
                        tableview.insertSections(NSIndexSet(index: insertIndex), withRowAnimation: .Automatic)
                    }
                    for deleteIndex in deletions {
                        tableview.deleteSections(NSIndexSet(index: deleteIndex), withRowAnimation: .Automatic)
                    }
                    for reloadIndex in modifications {
                        tableview.reloadSections(NSIndexSet(index: reloadIndex), withRowAnimation: .Automatic)
                    }
                    tableview.endUpdates()

这行得通。

但我想了解 'map' 以及如何使用它来映射部分。

 tableView.insertSections(insertions.map { NSIndexSet(index: [=13=]) }, withRowAnimation: .Automatic)

还有,

tableview.insertSections(insertions.map({ (index) -> NSIndexSet in
                        NSIndexSet(index: index)
                    }), withRowAnimation: .Automatic)

但是,两者都给我同样的错误

'map' produces '[T]', not the expected contextual result type 'NSIndexSet'

map returns 通过将每个原始集合元素替换为同一元素的映射版本来创建一个新集合。换句话说:

insertions.map { ...}

returns 一个数组,而 tableView.insertSections 需要一个 NSIndexSet 参数。

您最接近的是:

for indexSet in insertions.map { NSIndexSet(index: [=11=]) } {
    tableView.insertSections(indexSet, ...)
}

或者,您可以创建一个 NSIndexSet,它是使用 reduce 的各个元素的结合,例如:

tableView.insertSections(insertions.reduce(NSMutableIndexSet()) {
    [=12=].addIndex()
    return [=12=]
}, withRowAnimation: .Automatic)

但这似乎真的是在模糊而不是澄清代码。