Accessing view controller methods inside another class [Swift]

Published

I am using UITableViewDiffableDataSource for my table view’s dataSource by creating a UITableViewDiffableDataSource class inside my ViewController (AnimalsVC). Whenever I try to get my ViewController’s data array (or any variables/functions) from inside my data source class I get this error:

Instance member 'animalsArray' of type 'AnimalsVC' cannot be used on an instance of nested type 'AnimalsVC.DataSource'

I am not sure why getting this error because my DataSource class is inside my ViewController class. Here is my code:

class AnimalsVC: UIViewController {
   var animalsArray = []

   class DataSource: UITableViewDiffableDataSource<Int, Animal> {
      override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

         let items = animalsArray //<- This is where the error occurs   

         return true
      }
   }

}

Source: Ios

Published
Categorised as datasource, ios, swift, uitableview

Answers

In order to access the outer class from the inner, you need to pass a reference in to it. It is not automatic, as with Java, for instance.

Assuming the Animal object is defined elsewhere, then what you could do is:

class AnimalsVC: UIViewController {
   var animalsArray = [] as [Animal]

   class DataSource: UITableViewDiffableDataSource<Int, Animal> {

      var myanimal:AnimalsVC

      init(animal: AnimalsVC){
          myanimal = animal
          super.init()
      }

      override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

         let items = myanimal.animalsArray //<- This should not be an error any more   

         return true
      }
   }

}

Eileen Herzog

Leave a Reply

Your email address will not be published. Required fields are marked *

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq