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

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

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

gives 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'

+6
source share
2 answers

You need to highlight self.fetchedResultsController?.sections in the Array of NSFetchedResultsSectionInfo objects:

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

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

 if let s = self.fetchedResultsController?.sections as? [NSFetchedResultsSectionInfo] { d = s[section].numberOfObjects } 
+11
source

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

Works for me (Swift 2.1):

 if let sections = fetchedResultsController?.sections { return sections[section].numberOfObjects } else { return 0 } 
+3
source

Source: https://habr.com/ru/post/975599/


All Articles