Search code examples
iosswiftprotocolsnsfetchedresultscontroller

How can I get number of objects in section, NSFetchedResultsController Swift


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'


Solution

  • 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
    }