Search code examples
iosarraysswiftdrop-down-menuxcode9-beta

Use of unresolved identifier error when calling array in my extension code


I am trying to create a fairly simple drop down menu for which I have created an array with some strings to be displayed. I am not sure where I have gone wrong but the array "rList" does not get recognised when I write the extension code to add the array onto a UITableView to be displayed in the drop down. An unresolved identifier error shows up at the extension code where "rList" is called. Also note I am running on Xcode 9 beta not sure if there have been changes in some syntax that I may have missed. Appreciate any help I can get on this!

Cheers

(Heres the code)

import UIKit


    class MainViewController: UIViewController {



        @IBOutlet weak var tableView: UITableView!

        @IBOutlet weak var dropDownButton: UIButton!

        var rList = ["A", "B", "C", "D", "E", "F"]

        override func viewDidLoad() {
            super.viewDidLoad()
            self.tableView.isHidden = true
            // Do any additional setup after loading the view.

        }


        @IBAction func dropDownButtonPressed(_ sender: Any) {
            if tableView.isHidden {
            animate(toggle: true)
            } else {
                animate(toggle: false)
            }
        }


        func  animate(toggle:Bool) {
            if toggle {
                UIView.animate(withDuration: 0.3) {
                    self.tableView.isHidden = false
                }
            } else {
                UIView.animate(withDuration: 0.3) {

                    self.tableView.isHidden = true
                }
              }
            }
          }

Now for my extension code

extension ViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return rList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = rList[indexPath.row]
    return cell
    }
}

Solution

  • You are extending ViewController (which is the default empty view controller provided by an app template) instead of MainViewController. ViewController in its template form does not have rList as member, thus the error.

    Change your extension to:

    extension MainViewController: UITableViewDelegate, UITableViewDataSource {
    .
    .
    .
    }