10

How can I get number of objects in section of an NSFetchedResultcController in Swift?

    if let s = self.fetchedResultsController?.sections as? NSFetchedResultsSectionInfo {

    }

is giving me Cannot downcast from '[AnyObject]' to non-@objc protocol type NSFetchedResultsSectionInfo

 var d = self.fetchedResultsController?.sections[section].numberOfObjects

gives me does not have member named 'subscript'

SirRupertIII
  • 12,324
  • 20
  • 72
  • 121

3 Answers3

13

You need to cast self.fetchedResultsController?.sections to an Array of NSFetchedResultsSectionInfo objects:

if let s = self.fetchedResultsController?.sections as? [NSFetchedResultsSectionInfo]

Then you can pass the section to the subscript and get the number of objects:

if let s = self.fetchedResultsController?.sections as? [NSFetchedResultsSectionInfo] {
    d = s[section].numberOfObjects
}
Mike S
  • 41,895
  • 11
  • 89
  • 84
4

I think the currently accepted answer by Mike S was pre Swift 2.0

The following is working for me (Swift 2.1):

if let sections = fetchedResultsController?.sections {
    return sections[section].numberOfObjects
} else {
    return 0
}
So Over It
  • 3,668
  • 3
  • 35
  • 46
0

This is what I have in my UITableViewController (Swift 4):

override func numberOfSections(in tableView: UITableView) -> Int {
    guard let sections = fetchedResultsController.sections else { return 0 }
    return sections.count
}
KVISH
  • 12,923
  • 17
  • 86
  • 162